UNPKG

1.2 kBTypeScriptView Raw
1import type {RequiredKeysOf} from './required-keys-of';
2
3/**
4Creates a type that represents `true` or `false` depending on whether the given type has any required fields.
5
6This is useful when you want to create an API whose behavior depends on the presence or absence of required fields.
7
8@example
9```
10import type {HasRequiredKeys} from 'type-fest';
11
12type GeneratorOptions<Template extends object> = {
13 prop1: number;
14 prop2: string;
15} & (HasRequiredKeys<Template> extends true
16 ? {template: Template}
17 : {template?: Template});
18
19interface Template1 {
20 optionalSubParam?: string;
21}
22
23interface Template2 {
24 requiredSubParam: string;
25}
26
27type Options1 = GeneratorOptions<Template1>;
28type Options2 = GeneratorOptions<Template2>;
29
30const optA: Options1 = {
31 prop1: 0,
32 prop2: 'hi'
33};
34const optB: Options1 = {
35 prop1: 0,
36 prop2: 'hi',
37 template: {}
38};
39const optC: Options1 = {
40 prop1: 0,
41 prop2: 'hi',
42 template: {
43 optionalSubParam: 'optional value'
44 }
45};
46
47const optD: Options2 = {
48 prop1: 0,
49 prop2: 'hi',
50 template: {
51 requiredSubParam: 'required value'
52 }
53};
54
55```
56
57@category Utilities
58*/
59export type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;