Sub topic 10
Built-in Utility Types
TypeScript ships with a set of generic types that transform other types. You use them instead of writing the same mapped or conditional type by hand. This chapter assumes you know generic type aliases, keyof, indexed access types (T[K]), and the basics of mapped types from the earlier chapters.
Why utility types exist
Real code often needs a variation of a type you already have. An update function accepts some of an entity's fields. A list view shows only a few. A configuration object maps a fixed set of names to one value type. Copying and editing the original interface leads to drift: you change the interface and forget the copy.
Utility types derive the new type from the original, so there is one source of truth. Each one is an ordinary generic type alias that lives in TypeScript's standard library. You could write all of them yourself with the tools from the previous chapters.
The examples below use this type:
interface Todo {
title: string;
done: boolean;
notes: string;
}Utilities that reshape object types
Partial and Required
Partial<T> makes every property optional. Required<T> removes optionality from every property.
interface Todo {
title: string;
done: boolean;
notes: string;
}
type TodoDraft = Partial<Todo>;
// { title?: string; done?: boolean; notes?: string }
function updateTodo(todo: Todo, changes: Partial<Todo>): Todo {
return { ...todo, ...changes };
}
const base: Todo = { title: "Write", done: false, notes: "" };
const finished = updateTodo(base, { done: true });
console.log(finished.done); // truePartial is a mapped type with a ? modifier added. Required uses -? to remove the modifier. These two modifiers are the whole difference between them.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };Readonly
Readonly<T> marks every property as readonly. The chapter on mapped types showed a hand-written version.
interface Todo {
title: string;
done: boolean;
notes: string;
}
const frozen: Readonly<Todo> = { title: "Write", done: false, notes: "" };
// frozen.done = true; // Error: cannot assign to 'done' because it is a read-only propertyReadonly is shallow. It affects only the top-level properties, and a nested object or array can still be mutated through its own methods.
Pick and Omit
Pick<T, K> keeps only the listed keys. Omit<T, K> keeps everything except the listed keys.
interface Todo {
title: string;
done: boolean;
notes: string;
}
type TodoSummary = Pick<Todo, "title" | "done">;
// { title: string; done: boolean }
type TodoWithoutNotes = Omit<Todo, "notes">;
// { title: string; done: boolean }The two types are defined differently. Pick constrains its key parameter: K extends keyof T. A misspelled key is an error. Omit accepts any string | number | symbol for its key parameter, so a typo silently removes nothing.
interface Todo {
title: string;
done: boolean;
notes: string;
}
type Oops = Omit<Todo, "note">; // no error, and "notes" is still present
type Checked = Pick<Todo, "titel">; // Error: not assignable to keyof TodoThe looseness of Omit is deliberate. It lets you use it on union types and generic code where the keys are not known to exist on every member. The cost is that you must check your spelling yourself.
Record
Record<K, V> builds an object type whose keys are K and whose values are all V.
type Flags = Record<"dark" | "compact", boolean>;
// { dark: boolean; compact: boolean }
const flags: Flags = { dark: true, compact: false };
type Scores = Record<string, number>;
const scores: Scores = { ada: 10, grace: 12 };When K is a union of string literals, every key is required, so you get an exhaustiveness check: add a member to the union and every Record over it reports the missing property. When K is string, you get an index signature, and any key is allowed.
Utilities that work on unions
Exclude, Extract, and NonNullable
These three are conditional types that distribute over a union. They filter its members.
type Letters = "a" | "b" | "c";
type WithoutA = Exclude<Letters, "a">; // "b" | "c"
type OnlyAB = Extract<Letters, "a" | "b">; // "a" | "b"
type Defined = NonNullable<string | null | undefined>; // stringExclude<T, U>removes the members ofTthat are assignable toU.Extract<T, U>keeps only the members ofTthat are assignable toU.NonNullable<T>removesnullandundefined.
They are defined with the distributive conditional types covered in an earlier chapter:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;Returning never for a member makes it disappear from the resulting union, which is how the filtering works.
A common combination derives the keys of one type that hold a given kind of value:
interface Todo {
title: string;
done: boolean;
notes: string;
}
type KeysOfType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
type StringKeys = KeysOfType<Todo, string>; // "title" | "notes"
type PickedStrings = Pick<Todo, StringKeys>; // { title: string; notes: string }Utilities that inspect functions
ReturnType and Parameters
ReturnType<F> gives a function's return type. Parameters<F> gives its parameter list as a tuple. Both take a function type, so for a function value you apply typeof first.
interface Todo {
title: string;
done: boolean;
notes: string;
}
function makeTodo(title: string, done = false): Todo {
return { title, done, notes: "" };
}
type Made = ReturnType<typeof makeTodo>; // Todo
type Args = Parameters<typeof makeTodo>; // [title: string, done?: boolean]
function callLater(...args: Args): Todo {
return makeTodo(...args);
}Both use infer. This is a simplified form of ReturnType:
type MyReturnType<F extends (...args: any) => any> =
F extends (...args: any) => infer R ? R : any;Using ReturnType keeps a type tied to its function. If the function's return type changes, every type derived from it changes too, with no second declaration to update.
ReturnType<typeof f> on a generic function gives the result with type parameters replaced by their constraints, usually unknown. The utility cannot carry the type parameter through.
Awaited
Awaited<T> unwraps a promise type, recursively. It models what await produces.
async function fetchTodo(): Promise<{ title: string }> {
return { title: "Write" };
}
type Result = Awaited<ReturnType<typeof fetchTodo>>; // { title: string }
type Nested = Awaited<Promise<Promise<number>>>; // numberWithout Awaited, ReturnType<typeof fetchTodo> is Promise<{ title: string }>, which is rarely the type you want to name.
Constructor-related utilities
ConstructorParameters<C> and InstanceType<C> do for classes what Parameters and ReturnType do for functions.
class Stack<T> {
private items: T[] = [];
constructor(initial: T[] = []) {
this.items = initial;
}
}
type StackArgs = ConstructorParameters<typeof Stack>; // [initial?: unknown[]]
type StackInstance = InstanceType<typeof Stack>; // Stack<unknown>Composing utilities
Utility types are ordinary generics, so they nest. A typical case is an update payload where the identifier is required and the rest is optional:
interface User {
id: number;
name: string;
email: string;
}
type UserUpdate = Pick<User, "id"> & Partial<Omit<User, "id">>;
// { id: number } & { name?: string; email?: string }
function applyUpdate(user: User, update: UserUpdate): User {
return { ...user, ...update };
}
const updated = applyUpdate(
{ id: 1, name: "Ada", email: "[email protected]" },
{ id: 1, name: "Ada Lovelace" }
);
console.log(updated.name); // Ada LovelaceThe intersection form displays badly in editor tooltips. A small helper flattens it:
type Simplify<T> = { [K in keyof T]: T[K] } & {};It does not change what the type means, only how it is shown.
Gotchas
- Shallow transformation.
Partial,Readonly, andRequiredchange only the first level. A nested object keeps its original optionality and mutability. A recursiveDeepPartialis a custom type you write yourself. Omitdoes not check keys. A misspelled key removes nothing and raises no error.OmitandPickon unions. They are not distributive.Omit<A | B, "x">collapses the union into one object with only the shared keys. Write a distributive version when you need per-member behavior:type DistOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;.Record<string, V>hides missing keys. Indexing returnsV, notV | undefined, unless thenoUncheckedIndexedAccesscompiler option is on.- Types only. Utility types vanish at compile time.
Partial<Todo>does not make the runtime object validated or fill in defaults.
Choosing the right utility
| Goal | Utility |
|---|---|
| Make all fields optional | `Partial<T>` |
| Make all fields required | `Required<T>` |
| Prevent reassignment of fields | `Readonly<T>` |
| Keep some fields | `Pick<T, K>` |
| Drop some fields | `Omit<T, K>` |
| Map a key set to one value type | `Record<K, V>` |
| Filter union members | `Exclude`, `Extract`, `NonNullable` |
| Get a function's result or arguments | `ReturnType`, `Parameters` |
| Unwrap a promise | `Awaited<T>` |
Prefer a utility over a hand-written copy whenever one type is derived from another. Write a custom mapped or conditional type only when no built-in expresses the transformation.
Exercise
Given interface Config { host: string; port: number; debug: boolean }, write a type ConfigPatch in which host is required and every other field is optional. Then explain why Omit<Config, "hots"> compiles without an error.
Show answer
type ConfigPatch = Pick<Config, "host"> & Partial<Omit<Config, "host">>;. This gives { host: string } & { port?: number; debug?: boolean }. Omit declares its key parameter as K extends keyof any (that is, string | number | symbol) instead of keyof T, so the misspelled "hots" is an accepted key. It matches no property, so nothing is removed and the result is the full Config.
Exercise
What are the types of A and B?
type A = Exclude<"x" | "y" | "z", "y" | "z">;
type B = Awaited<ReturnType<() => Promise<Promise<string>>>>;
Show answer
A is "x", because Exclude removes the members assignable to "y" | "z". B is string: ReturnType yields Promise<Promise<string>>, and Awaited unwraps promises recursively down to string.