main
Last change
on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago |
Initial commit
|
-
Property mode
set to
100644
|
File size:
1.0 KB
|
Line | |
---|
1 | import {Except} from './except';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.
|
---|
5 |
|
---|
6 | Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.
|
---|
7 |
|
---|
8 | @example
|
---|
9 | ```
|
---|
10 | import {SetRequired} from 'type-fest';
|
---|
11 |
|
---|
12 | type Foo = {
|
---|
13 | a?: number;
|
---|
14 | b: string;
|
---|
15 | c?: boolean;
|
---|
16 | }
|
---|
17 |
|
---|
18 | type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
|
---|
19 | // type SomeRequired = {
|
---|
20 | // a?: number;
|
---|
21 | // b: string; // Was already required and still is.
|
---|
22 | // c: boolean; // Is now required.
|
---|
23 | // }
|
---|
24 | ```
|
---|
25 | */
|
---|
26 | export type SetRequired<BaseType, Keys extends keyof BaseType = keyof BaseType> =
|
---|
27 | // Pick just the keys that are not required from the base type.
|
---|
28 | Except<BaseType, Keys> &
|
---|
29 | // Pick the keys that should be required from the base type and make them required.
|
---|
30 | Required<Pick<BaseType, Keys>> extends
|
---|
31 | // If `InferredType` extends the previous, then for each key, use the inferred type key.
|
---|
32 | infer InferredType
|
---|
33 | ? {[KeyType in keyof InferredType]: InferredType[KeyType]}
|
---|
34 | : never;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.