Pick and Omit in Typescript

Pick and Omit are used to pick fields from a type to create a new type or, in the case of Omit, returns a type with supplied fields omitted.

For example, if we have a simple type such as this

type Person = {
  firstName: string
  lastName: string
  age: number
}

We might wish to create a new type based upon the Person type but with only the first name. We can use Pick to pick the fields like this

function pickSample(person: Pick<Person, "firstName">): string {
  return `Hello, ${person.firstName}!`
}

We can do the opposite using Omit, hence excluding fields

function omitSample(person: Omit<Person, "age">): string {
  return `Hello, ${person.firstName} ${person.lastName}`;
}