UNPKG

1.23 kBTypeScriptView Raw
1import type {Except} from './except';
2import type {Simplify} from './simplify';
3
4/**
5Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` 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 required.
8
9@example
10```
11import type {SetRequired} from 'type-fest';
12
13type Foo = {
14 a?: number;
15 b: string;
16 c?: boolean;
17}
18
19type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
20// type SomeRequired = {
21// a?: number;
22// b: string; // Was already required and still is.
23// c: boolean; // Is now required.
24// }
25```
26
27@category Object
28*/
29export type SetRequired<BaseType, Keys extends keyof BaseType> =
30 // `extends unknown` is always going to be the case and is used to convert any
31 // union into a [distributive conditional
32 // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
33 BaseType extends unknown
34 ? Simplify<
35 // Pick just the keys that are optional from the base type.
36 Except<BaseType, Keys> &
37 // Pick the keys that should be required from the base type and make them required.
38 Required<Pick<BaseType, Keys>>
39 >
40 : never;