Pick & Omit

Create new types by selecting or removing keys.

TypeScript4 min readConcept 38 of 54

Sub-setting Interfaces

Pick<Type, Keys> creates a new type by choosing a specific set of properties from an existing Type.

Omit<Type, Keys> does the exact opposite: it constructs a new type by taking all properties from Type and *removing* the specified Keys.

Single Source of Truth

Instead of manually creating a UserSummary interface that duplicates fields from the main User interface, you can derive it using Pick or Omit.

If the type of the email field changes in the main User interface, the derived types automatically update, preventing drift.

Syntax

typescript interface User { id: number; name: string; email: string; passwordHash: string; } // Whitelist: We only want these two type UserSummary = Pick<User, "name" | "email">; // Blacklist: We want everything EXCEPT these type SafeUser = Omit<User, "passwordHash">;

Try it

Toggle keys in the source interface and switch between Pick and Omit modes. Watch how the resulting type dynamically updates based on your selection.

Select Keys (Union)
// 1. The Source of Truth
interface User {
id: number;
name: string;
email: string;
password: string;
}

// 2. The Derived Type
type Derived =Pick<User,"name" | "email">;
Derived Shape
{
name: string;
email: string;
}

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Given `type A = { x: number, y: string }`, what happens if you write `type B = Pick<A, 'z'>`?

Remember this

  • Pick creates a new type containing ONLY the specified keys.
  • Omit creates a new type containing ALL keys EXCEPT the specified ones.
  • Pick throws an error if you pass a non-existent key.
  • Omit silently ignores non-existent keys.

Done with this concept?

Mark it complete to track your progress. No login needed.