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