Using TypeScript Pick and Omit utility types

TypeScript provides a number of utility types that can be used to create more specific or generic object types in your code. In this article, we'll take a look at the pick, omit, and other utility types, and see how they can be used to improve the type safety and flexibility of your code.

The Pick type creates a new object type by picking a set of properties from an existing object type. For example, if you have an object type Person with properties name and age, you can use the pick utility to create a new object type that includes only the name property:

type Person = {
name: string;
age: number;
}
type PersonName = Pick<Person, 'name'>;

In this example, the PersonName type will be equivalent to {name: string}.

The Omit type, on the other hand, creates a new object type by omitting a set of properties from an existing object type. Continuing with the previous example, you can use the omit utility to create a new object type that excludes the age property:

type Person = {
name: string;
age: number;
}
type PersonWithoutAge = Omit<Person, 'age'>;

In this example, the PersonWithoutAge type will be equivalent to {name: string} as well.

In addition to the Pick and Omit utility types, TypeScript provides several other utility types that can be useful for working with object types. Some of the more commonly used utility types include:

  • Partial<T>: Makes all properties of a type optional.
  • Readonly<T>: Makes all properties of a type read-only.
  • Record<K, T>: Creates a type with a set of properties of a given type, where the names of the properties are specified by a string union.
  • Exclude<T, U>: Excludes from a type those types that are assignable to a given type.
  • Extract<T, U>: Extracts from a type those types that are assignable to a given type.
  • NonNullable<T>: Excludes null and undefined from a type.

These utility types can be very useful when creating more complex or specific type definitions in your TypeScript code.


December 07, 2022
321