๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Pick, Omit and Record

Pick, Omit and Record build object types from other types and keys. Each one states exactly which properties the new type holds.

Keep two fields with Pick

Pick takes a type and the names to keep. The new type holds only those properties.

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

const card: Pick<User, "name" | "email"> = { name: "Ada", email: "ada@example.com" };
console.log(card);

Drop one field with Omit

Omit takes a type and the names to drop. The password field is gone from the new type.

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

const publicUser: Omit<User, "password"> = { id: 1, name: "Ada", email: "ada@example.com" };
console.log(publicUser);

Build a price map with Record

Record takes a key type and a value type. Every key in the object holds a value of that type.

const prices: Record<string, number> = { apple: 2, pear: 3 };
console.log(prices.apple);
console.log(Object.keys(prices));

Example

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

type Card = Pick<User, "name" | "email">;
type PublicUser = Omit<User, "password">;

const card: Card = { name: "Ada", email: "ada@example.com" };
const publicUser: PublicUser = { id: 1, name: "Ada", email: "ada@example.com" };
console.log(card);
console.log(publicUser);

Key points

  • Pick keeps only the named properties of a type
  • Omit keeps every property of a type except the named ones
  • Record builds an object type from a key type and a value type
  • Pick and Omit take the property names as string literals in a union
  • A type built with Pick or Omit stays based on the original type

In this example, one User interface gives two new types. Card keeps the name and email fields through Pick. PublicUser drops the password field through Omit. Both logged objects match their derived types.

Note

Record keys can be a string type, a number type or a union of literals

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

Which utility builds a type by dropping the named properties?