1 | import type {Except} from './except';
|
2 | import type {HomomorphicPick} from './internal';
|
3 | import type {KeysOfUnion} from './keys-of-union';
|
4 | import type {Simplify} from './simplify';
|
5 |
|
6 | /**
|
7 | Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type.
|
8 |
|
9 | Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional.
|
10 |
|
11 | @example
|
12 | ```
|
13 | import type {SetOptional} from 'type-fest';
|
14 |
|
15 | type Foo = {
|
16 | a: number;
|
17 | b?: string;
|
18 | c: boolean;
|
19 | }
|
20 |
|
21 | type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
|
22 | // type SomeOptional = {
|
23 | // a: number;
|
24 | // b?: string; // Was already optional and still is.
|
25 | // c?: boolean; // Is now optional.
|
26 | // }
|
27 | ```
|
28 |
|
29 | @category Object
|
30 | */
|
31 | export type SetOptional<BaseType, Keys extends keyof BaseType> =
|
32 | BaseType extends unknown // To distribute `BaseType` when it's a union type.
|
33 | ? Simplify<
|
34 | // Pick just the keys that are readonly from the base type.
|
35 | Except<BaseType, Keys> &
|
36 | // Pick the keys that should be mutable from the base type and make them mutable.
|
37 | Partial<HomomorphicPick<BaseType, Keys & KeysOfUnion<BaseType>>>
|
38 | >
|
39 | : never;
|