← All tasksTypeScript · Junior

keyof: pluck

pluck(items, key) returns an array of one field's values: pluck(users, "name") gives ["Ann", "Bob"].

Type it so that key can only be a real field of the objects (a typo is a compile error), and the result has that field's type: string[] for name, number[] for id.

Tests (6)

Type tests are checked by the TypeScript compiler in strict mode. Expect<Equal<A, B>> passes when the types match exactly, and // @ts-expect-error passes when the next line does not compile. The first run downloads the compiler, so it takes a few seconds.

  1. types
    const users = [{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }];
    const names = pluck(users, 'name');
    type _ = Expect<Equal<typeof names, string[]>>;
  2. types
    const users = [{ id: 1, name: 'Ann' }];
    const ids = pluck(users, 'id');
    type _ = Expect<Equal<typeof ids, number[]>>;
  3. types
    // @ts-expect-error - users have no email
    pluck([{ id: 1, name: 'Ann' }], 'email');
  4. const users = [{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }];
    expect(pluck(users, 'name')).toEqual(['Ann', 'Bob']);
  5. expect(pluck([{ id: 1 }, { id: 2 }], 'id')).toEqual([1, 2]);
  6. expect(pluck([], 'id')).toEqual([]);