TypeScript ยท Chapter 30 of 44

Partial, Pick, and Omit

`Pick<T, Keys>` creates a new type by selecting only certain properties from an existing type, while `Omit<T, Keys>` does the opposite, creating a new type with certain properties removed.

These utility types are extremely useful when you need a smaller or trimmed version of a larger type, such as showing only a subset of a User's fields in a public profile view.

Syntax
type PublicUser = Omit<User, "password">;
type NameOnly = Pick<User, "name">;

Pick

`Pick<User, "name">` produces a type containing only the name property from User, discarding all others.

Omit

`Omit<User, "password">` produces a type with every property of User except password, which is handy for hiding sensitive fields.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
  password: string;
}
type NameOnly = Pick<User, "name">;
const n: NameOnly = { name: "Eve" };
console.log(n);
Output
{ name: 'Eve' }

Pick keeps only the specified 'name' property from the User interface.

Example 2 (typescript)
interface User {
  name: string;
  age: number;
  password: string;
}
type PublicUser = Omit<User, "password">;
const pub: PublicUser = { name: "Eve", age: 29 };
console.log(pub);
Output
{ name: 'Eve', age: 29 }

Omit removes the password property, leaving all other properties intact.

Key points

  • Pick<T, Keys> selects only the listed properties from T.
  • Omit<T, Keys> removes the listed properties from T.
  • Both are useful for creating smaller, purpose-specific versions of a type.
  • Keys are given as string literals or a union of string literals.
๐Ÿ’ก Note: Pick and Omit are opposites of each other and are often used together when shaping API responses.

๐Ÿ“ Quick Quiz

1. What does Pick<User, "name"> produce?

2. What does Omit<User, "password"> produce?

3. How are keys specified in Pick and Omit?