DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Understanding `Pick` and `Partial` in TypeScript

TypeScript’s utility types help you avoid repetitive code when working with object shapes. Two of the most useful are Pick and Partial. Let’s break them down with a practical example.

Starting Point: The User Interface

interface User {
  id: number;
  name: string;
  age: number;
  email: string;
  password: string;
}
Enter fullscreen mode Exit fullscreen mode

This describes a typical User object with all required fields.


Pick<T, K> – Selecting Specific Properties

Pick creates a new type by selecting a subset of properties from another type.

type UpdateProps = Pick<User, "age" | "name" | "email">;
Enter fullscreen mode Exit fullscreen mode

Here:

  • T is the source type (User).
  • K is a union of property keys we want ("age" | "name" | "email").

The resulting UpdateProps is equivalent to:

type UpdateProps = {
  age: number;
  name: string;
  email: string;
};
Enter fullscreen mode Exit fullscreen mode

This is perfect when, for example, you only need a few fields for a user-update operation instead of the full user object.


Partial<T> – Making Properties Optional

Partial creates a new type where all properties are optional.

type UpdatedUserOptional = Partial<UpdateProps>;
Enter fullscreen mode Exit fullscreen mode

Now every property in UpdatePropsage, name, and email—becomes optional:

type UpdatedUserOptional = {
  age?: number;
  name?: string;
  email?: string;
};
Enter fullscreen mode Exit fullscreen mode

This is handy for update APIs where a client might send only the fields they want to change.


Putting It Together

Here’s a function that updates a user:

function updateUser(updatedProps: UpdatedUserOptional) {
  // Hit the database with only the provided fields
}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • You don’t need to pass all three properties.
  • TypeScript still ensures that if a property is provided, it matches the correct type (string for name, number for age, etc.).

Example usage:

updateUser({ name: "Alice" });         // ✅ Only name
updateUser({ email: "a@b.com", age: 30 }); // ✅ Name is optional
Enter fullscreen mode Exit fullscreen mode

Why This Matters

Using Pick and Partial together:

  • Reduces duplication (no rewriting property types).
  • Keeps types in sync with your source interface.
  • Gives you flexible yet type-safe update patterns.

Quick Summary

Utility What it Does Example
Pick<T, K> Choose a set of properties from a type `Pick<User, "name" "email">`
Partial<T> Make all properties in a type optional Partial<UpdateProps>

With these two tools, your TypeScript code stays DRY, safe, and easy to maintain.

Top comments (0)