2025-02-28•Abyan Dimas
5 TypeScript Utility Types You Should Know
TypeScript is powerful, but are you using its full potential? Utility types are built-in tools to transform types efficiently.
1. Partial
Makes all properties of a type optional. Great for update functions.
interface User {
id: number;
name: string;
email: string;
}
function updateUser(id: number, fields: Partial<User>) {
// fields.name is optional now
}
2. Pick<T, K>
Selects only specific keys from a type.
type UserSummary = Pick<User, 'id' | 'name'>;
// { id: number; name: string; }
3. Omit<T, K>
The opposite of Pick. Removes specific keys.
type UserWithoutEmail = Omit<User, 'email'>;
4. Record<K, T>
Creates an object type with specific keys and values.
const roles: Record<string, number> = {
'admin': 1,
'user': 2
};
5. Readonly
Prevents mutation of properties.
const config: Readonly<Config> = { endpoint: 'api.com' };
// config.endpoint = 'error'; // Error!