1 // TODO: Remove this when we target TypeScript >=3.5.
2 type _Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
5 Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.
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`.
11 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.
15 import {RequireExactlyOne} from 'type-fest';
23 const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
24 // Adding a `text` key here would cause a compile error.
26 json: () => '{"message": "ok"}',
31 export type RequireExactlyOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
33 Required<Pick<ObjectType, Key>> &
34 Partial<Record<Exclude<KeysType, Key>, never>>
35 )}[KeysType] & _Omit<ObjectType, KeysType>;