UNPKG

921 BTypeScriptView Raw
1/**
2Extract all required keys from the given type.
3
4This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...
5
6@example
7```
8import type {RequiredKeysOf} from 'type-fest';
9
10declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
11
12interface User {
13 name: string;
14 surname: string;
15
16 luckyNumber?: number;
17}
18
19const validator1 = createValidation<User>('name', value => value.length < 25);
20const validator2 = createValidation<User>('surname', value => value.length < 25);
21```
22
23@category Utilities
24*/
25export type RequiredKeysOf<BaseType extends object> = Exclude<{
26 [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
27 ? Key
28 : never
29}[keyof BaseType], undefined>;