UNPKG

1.1 kBTypeScriptView Raw
1/**
2Create a type that makes the given keys non-nullable, where the remaining keys are kept as is.
3
4If no keys are given, all keys will be made non-nullable.
5
6Use-case: You want to define a single model where the only thing that changes is whether or not some or all of the keys are non-nullable.
7
8@example
9```
10import type {SetNonNullable} from 'type-fest';
11
12type Foo = {
13 a: number | null;
14 b: string | undefined;
15 c?: boolean | null;
16}
17
18type SomeNonNullable = SetNonNullable<Foo, 'b' | 'c'>;
19// type SomeNonNullable = {
20// a: number | null;
21// b: string; // Can no longer be undefined.
22// c?: boolean; // Can no longer be null, but is still optional.
23// }
24
25type AllNonNullable = SetNonNullable<Foo>;
26// type AllNonNullable = {
27// a: number; // Can no longer be null.
28// b: string; // Can no longer be undefined.
29// c?: boolean; // Can no longer be null, but is still optional.
30// }
31```
32
33@category Object
34*/
35export type SetNonNullable<BaseType, Keys extends keyof BaseType = keyof BaseType> = {
36 [Key in keyof BaseType]: Key extends Keys
37 ? NonNullable<BaseType[Key]>
38 : BaseType[Key];
39};