← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
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.
- types
const users = [{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }]; const names = pluck(users, 'name'); type _ = Expect<Equal<typeof names, string[]>>;
- types
const users = [{ id: 1, name: 'Ann' }]; const ids = pluck(users, 'id'); type _ = Expect<Equal<typeof ids, number[]>>;
- types
// @ts-expect-error - users have no email pluck([{ id: 1, name: 'Ann' }], 'email');
const users = [{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }]; expect(pluck(users, 'name')).toEqual(['Ann', 'Bob']);
expect(pluck([{ id: 1 }, { id: 2 }], 'id')).toEqual([1, 2]);
expect(pluck([], 'id')).toEqual([]);