1 | import type {Except} from './except';
|
2 |
|
3 | /**
|
4 | Create a type that requires at least one of the given keys. The remaining keys are kept as is.
|
5 |
|
6 | @example
|
7 | ```
|
8 | import type {RequireAtLeastOne} from 'type-fest';
|
9 |
|
10 | type Responder = {
|
11 | text?: () => string;
|
12 | json?: () => string;
|
13 | secure?: boolean;
|
14 | };
|
15 |
|
16 | const responder: RequireAtLeastOne<Responder, 'text' | 'json'> = {
|
17 | json: () => '{"message": "ok"}',
|
18 | secure: true
|
19 | };
|
20 | ```
|
21 |
|
22 | @category Object
|
23 | */
|
24 | export type RequireAtLeastOne<
|
25 | ObjectType,
|
26 | KeysType extends keyof ObjectType = keyof ObjectType,
|
27 | > = {
|
28 | // For each `Key` in `KeysType` make a mapped type:
|
29 | [Key in KeysType]-?: Required<Pick<ObjectType, Key>> & // 1. Make `Key`'s type required
|
30 | // 2. Make all other keys in `KeysType` optional
|
31 | Partial<Pick<ObjectType, Exclude<KeysType, Key>>>;
|
32 | }[KeysType] &
|
33 | // 3. Add the remaining keys not in `KeysType`
|
34 | Except<ObjectType, KeysType>;
|