source: trip-planner-front/node_modules/type-fest/source/require-exactly-one.d.ts@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.2 KB
Line 
1// TODO: Remove this when we target TypeScript >=3.5.
2type _Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
3
4/**
5Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.
6
7Use-cases:
8- Creating interfaces for components that only need one of the keys to display properly.
9- Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`.
10
11The caveat with `RequireExactlyOne` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireExactlyOne` can't do anything to prevent extra keys it doesn't know about.
12
13@example
14```
15import {RequireExactlyOne} from 'type-fest';
16
17type Responder = {
18 text: () => string;
19 json: () => string;
20 secure: boolean;
21};
22
23const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
24 // Adding a `text` key here would cause a compile error.
25
26 json: () => '{"message": "ok"}',
27 secure: true
28};
29```
30*/
31export type RequireExactlyOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
32 {[Key in KeysType]: (
33 Required<Pick<ObjectType, Key>> &
34 Partial<Record<Exclude<KeysType, Key>, never>>
35 )}[KeysType] & _Omit<ObjectType, KeysType>;
Note: See TracBrowser for help on using the repository browser.