Skip to content

pick function ​

Copies some properties of an object into a new one. Keys absent from the object are left out.

ts
import { pick } from 'utils';

Signature ​

ts
export function pick<T extends object, K extends keyof T>(object: T, keys: readonly K[]): Pick<T, K>

Parameters ​

NameDescription
TThe type of the object.
KThe keys to keep.
objectThe source object.
keysThe keys to copy.

Returns ​

A new object with only those keys.

Example ​

ts
pick({ id: 1, name: 'Pump', rpm: 800 }, ['id', 'name']); // { id: 1, name: 'Pump' }

Tests ​

Line coverage: 100 %.

  • ✅ keeps the requested keys
  • ✅ leaves absent keys out and does not modify the source
  • ✅ ignores inherited properties

Source ​

src/object/pick.ts (on GitHub)

Source code
ts
/**
 * Copies some properties of an object into a new one. Keys absent from the object are left out.
 *
 * @template T - The type of the object.
 * @template K - The keys to keep.
 * @param object - The source object.
 * @param keys - The keys to copy.
 * @returns A new object with only those keys.
 * @example
 * pick({ id: 1, name: 'Pump', rpm: 800 }, ['id', 'name']); // { id: 1, name: 'Pump' }
 */
export function pick<T extends object, K extends keyof T>(object: T, keys: readonly K[]): Pick<T, K> {
  const result: Partial<Pick<T, K>> = {};
  for (const key of keys) {
    if (Object.hasOwn(object, key)) {
      result[key] = object[key];
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- Every requested own key is copied.
  return result as Pick<T, K>;
}
Test file
ts
import { pick } from './pick';

class WithInheritedGetter {
  private readonly value = true;

  public get inherited(): boolean {
    return this.value;
  }
}

describe(pick, () => {
  it('keeps the requested keys', () => {
    expect(pick({ id: 1, name: 'Pump', rpm: 800 }, ['id', 'name'])).toStrictEqual({ id: 1, name: 'Pump' });
  });

  it('leaves absent keys out and does not modify the source', () => {
    const source: { id: number; label?: string } = { id: 1 };
    expect(pick(source, ['id', 'label'])).toStrictEqual({ id: 1 });
    expect(source).toStrictEqual({ id: 1 });
  });

  it('ignores inherited properties', () => {
    expect(pick(new WithInheritedGetter(), ['inherited'])).toStrictEqual({});
  });
});

Keywords: pick, objects, function

Generated from the JSDoc of the sources.