UNPKG

1.33 kBTypeScriptView Raw
1import type {NonRecursiveType, StringToNumber} from './internal';
2import type {Paths} from './paths';
3import type {SimplifyDeep} from './simplify-deep';
4import type {UnknownArray} from './unknown-array';
5
6/**
7Create a type that makes the given keys required. You can specify deeply nested key paths. The remaining keys are kept as is.
8
9Use-case: Selectively make nested properties required in complex types like models.
10
11@example
12```
13import type {SetRequiredDeep} from 'type-fest';
14
15type Foo = {
16 a?: number;
17 b?: string;
18 c?: {
19 d?: number
20 }[]
21}
22
23type SomeRequiredDeep = SetRequiredDeep<Foo, 'a' | `c.${number}.d`>;
24// type SomeRequiredDeep = {
25// a: number; // Is now required
26// b?: string;
27// c: {
28// d: number // Is now required
29// }[]
30// }
31```
32
33@category Object
34*/
35export type SetRequiredDeep<BaseType, KeyPaths extends Paths<BaseType>> =
36BaseType extends NonRecursiveType
37 ? BaseType
38 : SimplifyDeep<(
39 BaseType extends UnknownArray
40 ? {}
41 : {[K in keyof BaseType as K extends (KeyPaths | StringToNumber<KeyPaths & string>) ? K : never]-?: BaseType[K]}
42 ) & {
43 [K in keyof BaseType]: Extract<KeyPaths, `${K & (string | number)}.${string}`> extends never
44 ? BaseType[K]
45 : SetRequiredDeep<BaseType[K], KeyPaths extends `${K & (string | number)}.${infer Rest extends Paths<BaseType[K]>}` ? Rest : never>
46 }>;