Skip to content

Implementing a Custom Utility Type: Pick

Implement the built-in Pick<T, K> generic without using it.

Pick is a utility type in TypeScript that allows you to create a new type by picking a set of properties from an existing type.

Syntax:

Pick<Type, Keys>

Example

type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};

type BasicUserInfo = Pick<User, 'id' | 'name'>;

// Equivalent to:
type BasicUserInfo = {
  id: number;
  name: string;
};

// Usage
const user: BasicUserInfo = {
  id: 1,
  name: "John Doe",
};

Solution

The custom Pick type uses a mapped type to iterate over a subset of keys (K) from a given type (T), creating a new type with only those selected properties.

It ensures type safety by restricting K to valid keys of T using K extends keyof T.

type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};

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

// Usage
const user: MyPick<User, "name" | "email"> = {
  name: "John Doe",
  email: "john@example.com",
};

console.log(user)

/*
Output:
{
  "name": "John Doe",
  "email": "john@example.com"
} 
*/

Summary

References