What are Utility Types in TypeScript?
Utility types in TypeScript are built-in generic types that help transform or construct new types based on existing ones. They simplify type manipulations, making your code safer and more expressive. Here are some of the most commonly used utility types:
1. Partial<Type>
- Purpose: Makes all properties of a type optional.
- When to use: When you want to update part of an object or have optional fields temporarily.
-
Example:
type User = { id: number; name: string; age: number }; let userUpdate: Partial<User> = { name: "Alice" }; // userUpdate only needs to provide any subset of User's fields
2. Readonly<Type>
- Purpose: Makes all properties of a type immutable.
- When to use: When you want to prevent object properties from being changed after creation.
-
Example:
type Config = { apiKey: string; timeout: number }; const config: Readonly<Config> = { apiKey: "123", timeout: 500 }; // config.apiKey = "456"; // Error: cannot assign to 'apiKey' because it is a read-only property
3. Pick<Type, Keys>
- Purpose: Constructs a type by picking a set of properties from another type.
- When to use: When you only need a subset of object properties.
-
Example:
type User = { id: number; name: string; age: number }; type UsernameOnly = Pick<User, "name">; // UsernameOnly is { name: string }
4. Record<Keys, Type>
-
Purpose: Constructs a type with a set of properties
Keys, each of typeType. - When to use: When you want to map keys to values of a consistent type, like dictionaries or lookup tables.
-
Example:
type ErrorMessages = Record<string, string>; const errors: ErrorMessages = { "404": "Not Found", "500": "Server Error" };
Summary Table
| Utility | Use Case Example |
|---|---|
| Partial | Optional update objects |
| Readonly | Prevent mutation after creation |
| Pick | Selecting some fields from a type |
| Record | Dictionaries with typed values |
Mastering these utility types will help you write cleaner, more flexible, and type-safe TypeScript code.
This article was originally published by DEV Community and written by Jeferson Eiji.
Read original article on DEV Community