UNPKG

893 BTypeScriptView Raw
1/**
2Extract all optional keys from the given type.
3
4This is useful when you want to create a new type that contains different type values for the optional keys only.
5
6@example
7```
8import type {OptionalKeysOf, Except} from 'type-fest';
9
10interface User {
11 name: string;
12 surname: string;
13
14 luckyNumber?: number;
15}
16
17const REMOVE_FIELD = Symbol('remove field symbol');
18type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
19 [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
20};
21
22const update1: UpdateOperation<User> = {
23 name: 'Alice'
24};
25
26const update2: UpdateOperation<User> = {
27 name: 'Bob',
28 luckyNumber: REMOVE_FIELD
29};
30```
31
32@category Utilities
33*/
34export type OptionalKeysOf<BaseType extends object> = Exclude<{
35 [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
36 ? never
37 : Key
38}[keyof BaseType], undefined>;