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.
interface User {id: number;name: string;email: string;}const updateUser = (user: Partial<User>) => {// Now all properties of User are optional.console.log(user);};updateUser({ name: 'John' }); // ValidupdateUser({}); // Valid
2. Pick<T, K>
Description: Constructs a type by picking a set of properties
K
fromT
.Use case: When you want to create a new type with a subset of properties from an existing type.
interface User {id: number;name: string;email: string;}type UserPreview = Pick<User, 'id' | 'name'>;const user: UserPreview = {id: 1,name: 'John',};console.log(user); // Only `id` and `name` are required.
3. Omit<T, K>
Description: Constructs a type by omitting a set of properties
K
fromT
.Use case: When you want to exclude certain properties from an existing type.
interface User {id: number;name: string;email: string;}type UserWithoutEmail = Omit<User, 'email'>;const user: UserWithoutEmail = {id: 1,name: 'John',};console.log(user); // Only `id` and `name` are required.
4. Record<K, T>
Description: Constructs a type with a set of properties
K
of typeT
.Use case: When you want to map a set of keys to a specific type.
type Role = 'admin' | 'editor' | 'viewer';const roles: Record<Role, boolean> = {admin: true,editor: false,viewer: true,};console.log(roles); // Each role maps to a boolean value.
Summary Table:
Utility Type | Purpose | Example Use Case |
---|---|---|
Partial | Makes all properties optional in a given type. | Updating objects with optional fields. |
Pick | Selects a subset of properties from a type. | Creating a minimal type for previews. |
Omit | Excludes a subset of properties from a type. | Removing sensitive fields from an API response. |
Record | Maps a set of keys to a specified type. | Creating objects with fixed keys and specific types. |