This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Typescript

Utility Types: Learn TypeScript’s built-in utility types like Partial, Pick, Omit, and Record

TypeScript provides a set of utility types that help manipulate types in various ways, making it easier to write flexible and reusable code.

Let's explore some of the most commonly used utility types: Partial, Pick, Omit, and Record.

1. Partial<T>

  • Description: Constructs a type with all the properties of T set to optional.

  • Use case: When you want to create a version of an object type where all fields are optional.

1interface User {
2 id: number;
3 name: string;
4 email: string;
5}
6
7const updateUser = (user: Partial<User>) => {
8 // Now all properties of User are optional.
9 console.log(user);
10};
11
12updateUser({ name: 'John' }); // Valid
13updateUser({}); // Valid
14

2. Pick<T, K>

  • Description: Constructs a type by picking a set of properties K from T.

  • Use case: When you want to create a new type with a subset of properties from an existing type.

1interface User {
2 id: number;
3 name: string;
4 email: string;
5}
6
7type UserPreview = Pick<User, 'id' | 'name'>;
8
9const user: UserPreview = {
10 id: 1,
11 name: 'John',
12};
13
14console.log(user); // Only `id` and `name` are required.
15

3. Omit<T, K>

  • Description: Constructs a type by omitting a set of properties K from T.

  • Use case: When you want to exclude certain properties from an existing type.

1interface User {
2 id: number;
3 name: string;
4 email: string;
5}
6
7type UserWithoutEmail = Omit<User, 'email'>;
8
9const user: UserWithoutEmail = {
10 id: 1,
11 name: 'John',
12};
13
14console.log(user); // Only `id` and `name` are required.
15

4. Record<K, T>

  • Description: Constructs a type with a set of properties K of type T.

  • Use case: When you want to map a set of keys to a specific type.

1type Role = 'admin' | 'editor' | 'viewer';
2
3const roles: Record<Role, boolean> = {
4 admin: true,
5 editor: false,
6 viewer: true,
7};
8
9console.log(roles); // Each role maps to a boolean value.
10

Summary Table:

Utility TypePurposeExample Use Case
PartialMakes all properties optional in a given type.Updating objects with optional fields.
PickSelects a subset of properties from a type.Creating a minimal type for previews.
OmitExcludes a subset of properties from a type.Removing sensitive fields from an API response.
RecordMaps a set of keys to a specified type.Creating objects with fixed keys and specific types.