-
-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathrequire-all-or-none.d.ts
More file actions
54 lines (43 loc) · 1.6 KB
/
require-all-or-none.d.ts
File metadata and controls
54 lines (43 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type {If} from './if.d.ts';
import type {IfNotAnyOrNever, RequireNone} from './internal/index.d.ts';
import type {IsAny} from './is-any.d.ts';
import type {IsNever} from './is-never.d.ts';
/**
Requires all of the keys in the given object.
*/
type RequireAll<ObjectType, KeysType extends keyof ObjectType> = Required<Pick<ObjectType, KeysType>>;
/**
Create a type that requires all of the given keys or none of the given keys. The remaining keys are kept as is.
Use-cases:
- Creating interfaces for components with mutually-inclusive keys.
The caveat with `RequireAllOrNone` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireAllOrNone` can't do anything to prevent extra keys it doesn't know about.
@example
```
import type {RequireAllOrNone} from 'type-fest';
type Responder = {
text?: () => string;
json?: () => string;
secure: boolean;
};
const responder1: RequireAllOrNone<Responder, 'text' | 'json'> = {
secure: true,
};
const responder2: RequireAllOrNone<Responder, 'text' | 'json'> = {
text: () => '{"message": "hi"}',
json: () => '{"message": "ok"}',
secure: true,
};
```
@category Object
*/
export type RequireAllOrNone<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
IfNotAnyOrNever<ObjectType,
If<IsNever<KeysType>,
ObjectType,
_RequireAllOrNone<ObjectType, If<IsAny<KeysType>, keyof ObjectType, KeysType>>
>>;
type _RequireAllOrNone<ObjectType, KeysType extends keyof ObjectType> = (
| RequireAll<ObjectType, KeysType>
| RequireNone<KeysType>
) & Omit<ObjectType, KeysType>; // The rest of the keys.
export {};