Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 1.25 KB

File metadata and controls

45 lines (36 loc) · 1.25 KB

Home > types-kit > PickExactlyOne

PickExactlyOne type

Create a type that requires at least one of the given keys. The remaining keys are kept as is.

Signature:

export type PickExactlyOne<T, K extends Keys<T>> = StrictOmit<T, K> &
  {
    [P in K]: Required<Pick<T, P>> &
      Partial<{
        [Q in keyof T as Q extends Exclude<K, P> ? Q : never]: never
      }>
  }[K]

References: Keys, StrictOmit

Example

    interface Responder {
      text?: () => string;
      json?: () => string;
      secure?: boolean;
    };
    const responder1: PickExactlyOne<Responder, 'text' | 'json'> = {
      json: () => '{"message": "ok"}',
      secure: true
    };
    const responder2: PickExactlyOne<Responder, 'text' | 'json'> = {
      text: () => '{"message": "ok"}',
      secure: true
    };
    const responder2: PickExactlyOne<Responder, 'text' | 'json'> = {
      text: () => '{"message": "ok"}', // throw error
      json: () => '{"message": "ok"}',
      secure: true
    };