UNPKG

1.1 kBTypeScriptView Raw
1import type {Simplify} from './simplify';
2
3// Returns `never` if the key is optional otherwise return the key type.
4type RequiredFilter<Type, Key extends keyof Type> = undefined extends Type[Key]
5 ? Type[Key] extends undefined
6 ? Key
7 : never
8 : Key;
9
10// Returns `never` if the key is required otherwise return the key type.
11type OptionalFilter<Type, Key extends keyof Type> = undefined extends Type[Key]
12 ? Type[Key] extends undefined
13 ? never
14 : Key
15 : never;
16
17/**
18Enforce optional keys (by adding the `?` operator) for keys that have a union with `undefined`.
19
20@example
21```
22import type {EnforceOptional} from 'type-fest';
23
24type Foo = {
25 a: string;
26 b?: string;
27 c: undefined;
28 d: number | undefined;
29};
30
31type FooBar = EnforceOptional<Foo>;
32// => {
33// a: string;
34// b?: string;
35// c: undefined;
36// d?: number;
37// }
38```
39
40@internal
41@category Object
42*/
43export type EnforceOptional<ObjectType> = Simplify<{
44 [Key in keyof ObjectType as RequiredFilter<ObjectType, Key>]: ObjectType[Key]
45} & {
46 [Key in keyof ObjectType as OptionalFilter<ObjectType, Key>]?: Exclude<ObjectType[Key], undefined>
47}>;