UNPKG

1.17 kBTypeScriptView Raw
1import type {Except} from './except';
2import type {HomomorphicPick} from './internal';
3import type {KeysOfUnion} from './keys-of-union';
4import type {Simplify} from './simplify';
5
6/**
7Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type.
8
9Use-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```
13import type {SetOptional} from 'type-fest';
14
15type Foo = {
16 a: number;
17 b?: string;
18 c: boolean;
19}
20
21type 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*/
31export 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;