Skip to content

PickByType type ​

Keeps the properties whose type matches.

ts
import type { PickByType } from 'utils';

Signature ​

ts
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;

Parameters ​

NameDescription
TThe object type.
VThe property type to keep.

Example ​

ts
type Flags = PickByType<Settings, boolean>;

Tests ​

Line coverage: 0 %.

  • ✅ keeps the matching properties
  • ✅ lists the keys of matching properties

Source ​

src/types/pick-by-type.ts (on GitHub)

Source code
ts
/**
 * Lists the keys of the properties whose type matches: the numeric fields of a record to chart, the
 * boolean flags of a settings object.
 *
 * @template T - The object type.
 * @template V - The property type to look for.
 * @example
 * type NumericField = KeysOfType<Sample, number>; // 'speed' | 'heading'
 */
export type KeysOfType<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];

/**
 * Keeps the properties whose type matches.
 *
 * @template T - The object type.
 * @template V - The property type to keep.
 * @example
 * type Flags = PickByType<Settings, boolean>;
 */
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;
Test file
ts
import type { KeysOfType, PickByType } from './pick-by-type';

describe('PickByType', () => {
  it('keeps the matching properties', () => {
    expectTypeOf<PickByType<{ a: string; b: number; c: string }, string>>().toEqualTypeOf<{ a: string; c: string }>();
  });
});

describe('KeysOfType', () => {
  it('lists the keys of matching properties', () => {
    interface Sample {
      name: string;
      speed: number;
      heading: number;
      isValid?: boolean;
    }
    expectTypeOf<KeysOfType<Sample, number>>().toEqualTypeOf<'heading' | 'speed'>();
    expectTypeOf<KeysOfType<Sample, boolean | undefined>>().toEqualTypeOf<'isValid'>();
  });
});

Keywords: pick, by, type, types

Generated from the JSDoc of the sources.