Utility types
TypeScript ships with built-in utility types that transform one type into another. Instead of writing near-duplicate interfaces by hand, you derive them, and they stay in sync automatically when the original changes.
We'll use this User type throughout:
interface User {
id: number;
name: string;
email: string;
password: string;
role: 'admin' | 'member';
}Partial<T> and Required<T>
Partial makes every property optional, which is perfect for updates:
Pick<T, Keys> and Omit<T, Keys>
Select or remove properties:
Omit<User, 'password'> for API responses is a real-world security pattern: the compiler stops you from sending password hashes to clients.
Readonly<T>
Record<Keys, Value>
Build an object type from a set of keys:
Working with functions: ReturnType, Parameters, Awaited
Extract types from existing functions, which is handy when a library doesn't export the types you need:
Working with unions: Exclude, Extract, NonNullable
Cheat sheet
| Utility | Does |
|---|---|
Partial<T> |
All properties optional |
Required<T> |
All properties required |
Readonly<T> |
All properties read-only |
Pick<T, K> |
Only keys K |
Omit<T, K> |
All except keys K |
Record<K, V> |
An object with keys K and values V |
Exclude<U, X> / Extract<U, X> |
Remove / keep union members |
NonNullable<T> |
Remove null and undefined |
ReturnType<F> / Parameters<F> |
A function's return / parameter types |
Awaited<T> |
Unwrap a Promise |
Practice
Given the Product type, derive (don't rewrite!) these:
ProductInput: what a form submits (noid,createdAtorrating).ProductPatch: an update where any field exceptidis optional, andidis required.ProductCard: justname,priceandimageUrl, all read-only.
1.Which utility type creates a type with every property optional?
2.Why prefer Omit<User, 'password'> over writing a separate PublicUser interface by hand?