Skip to content
TypeScript types · Core · about 10 minutes

Pick, by hand

Write the type MyPick<T, K>: the object type that has only the keys K of T, with the same value types. K must be limited to keys of T, so a key that is not in T is a type error. Keep readonly and optional as they are in T. Do not use the built-in Pick.

Start from

// Replace any with a mapped type.
type MyPick<T, K> = any;

Not allowed here, so the type is written by hand: Pick.

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Limit K with a constraint: K extends keyof T.

  2. Hint 2

    A mapped type loops over a union of keys: { [P in K]: T[P] }.

Solution

From here on the page gives the method away. If you are still solving, go back to the hints.

TypeScript
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };

The checks it must pass

type _1 = Expect<Equal<MyPick<{ id: number; name: string; done: boolean }, "id">, { id: number }>>;
type _2 = Expect<Equal<MyPick<{ id: number; name: string; done: boolean }, "id" | "done">, { id: number; done: boolean }>>;
type _3 = Expect<Equal<MyPick<{ readonly id: number; name?: string; done: boolean }, "id" | "name">, { readonly id: number; name?: string }>>;
// @ts-expect-error
type _4 = MyPick<{ id: number }, "missing">;

What an interviewer looks for

It is the first mapped type interviewers ask for. It shows keyof, a generic constraint and indexed access in one line.