1 // TODO: Remove this when we target TypeScript >=3.5.
2 // eslint-disable-next-line @typescript-eslint/generic-type-naming
3 type _Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
6 Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.
9 - Creating interfaces for components that only need one of the keys to display properly.
10 - Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`.
12 The 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.
16 import {RequireExactlyOne} from 'type-fest';
24 const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
25 // Adding a `text` key here would cause a compile error.
27 json: () => '{"message": "ok"}',
32 export type RequireExactlyOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
34 Required<Pick<ObjectType, Key>> &
35 Partial<Record<Exclude<KeysType, Key>, never>>
36 )}[KeysType] & _Omit<ObjectType, KeysType>;