CodeWithMihir

TypeScript Tutorial

TypeScript Pick Utility Type Explained

Learn how the Pick utility type works in TypeScript, including selecting object properties, creating smaller types, and practical examples.

Welcome back! I am Mihir, and in this lesson we will learn the Pick utility type in TypeScript.

Pick<T, K> creates a new type by selecting specific properties from another type.


Basic Pick Example

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

type PublicUser = Pick<User, "id" | "name">;

PublicUser behaves like:

type PublicUser = {
  id: number;
  name: string;
};

Using Pick

const user: PublicUser = {
  id: 1,
  name: "Mihir",
};

Invalid:

const user: PublicUser = {
  id: 1,
  name: "Mihir",
  email: "mihir@example.com",
};

email was not picked.


Useful for API Responses

type UserProfile = Pick<User, "id" | "name" | "email">;

This avoids exposing sensitive fields like password.


Pick Requires Valid Keys

Invalid:

type BadUser = Pick<User, "age">;

age is not a key of User.

TypeScript catches the mistake.


Pick with Function Parameters

function sendWelcomeEmail(user: Pick<User, "name" | "email">) {
  console.log(`Hello ${user.name}, email sent to ${user.email}`);
}

The function only asks for the fields it needs.


Quick Recap

  • Pick<T, K> selects properties from a type.
  • K must be valid keys of T.
  • It is useful for API responses and focused function parameters.
  • It helps avoid duplicating similar object types.
  • It can help hide sensitive or unnecessary fields.

Next up, we will learn Omit →.