UNPKG

872 BTypeScriptView Raw
1import type {Except} from './except';
2
3/**
4Create a type that requires at least one of the given keys. The remaining keys are kept as is.
5
6@example
7```
8import type {RequireAtLeastOne} from 'type-fest';
9
10type Responder = {
11 text?: () => string;
12 json?: () => string;
13 secure?: boolean;
14};
15
16const responder: RequireAtLeastOne<Responder, 'text' | 'json'> = {
17 json: () => '{"message": "ok"}',
18 secure: true
19};
20```
21
22@category Object
23*/
24export 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`
34Except<ObjectType, KeysType>;