UNPKG

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