The Built-in Utility Types
A guided tour of the standard library of type transformers you get for free.
TypeScript ships a toolbox of ready-made utility types. You have met a few; here is the wider family, grouped by what they do.
Reshaping objects
Partial<T>/Required<T>— toggle optionality on every field.Readonly<T>— freeze every field.Pick<T, K>/Omit<T, K>— keep or drop named keys.Record<K, V>— build a dictionary from a key union.
Filtering unions
Exclude<U, X>/Extract<U, X>— remove or keep union members.NonNullable<T>— stripnullandundefined.
Inspecting functions
ReturnType<F>,Parameters<F>,ConstructorParameters<C>,InstanceType<C>.Awaited<T>— the value a promise resolves to, unwrapped recursively.
Every one of these is built from the mapped and conditional types you just learned — nothing magic, just well-named building blocks.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A developer uses Exclude and Extract to split a large union type into two smaller, specialised types.
- A function's return type is captured with ReturnType so changes to the function signature propagate automatically.
- A parameters object is typed with Parameters<typeof fn>[0] to reuse the exact first-argument type of an existing function.
More examples
Exclude and Extract
Extract keeps only union members assignable to the second argument; Exclude removes them, complementing each other.
type AllEvents = 'click' | 'keydown' | 'scroll' | 'focus';
type MouseEvents = Extract<AllEvents, 'click' | 'scroll'>; // 'click' | 'scroll'
type OtherEvents = Exclude<AllEvents, 'click' | 'scroll'>; // 'keydown' | 'focus'ReturnType and Parameters
ReturnType and Parameters extract the return and parameter types from an existing function without re-declaring them.
function parseUser(raw: string): { id: number; name: string } {
return JSON.parse(raw);
}
type UserResult = ReturnType<typeof parseUser>; // { id: number; name: string }
type ParseInput = Parameters<typeof parseUser>[0]; // stringNonNullable and Awaited
NonNullable strips null and undefined from a union; Awaited unwraps the resolved type of a Promise return value.
type Nullable = string | number | null | undefined;
type Clean = NonNullable<Nullable>; // string | number
async function loadUser(): Promise<{ name: string }> {
return { name: 'Alice' };
}
type Resolved = Awaited<ReturnType<typeof loadUser>>; // { name: string }
Discussion