Utility types

Advanced

Introduction

Programs need many variations of the same shape: a user, the fields of a user that can be updated, the public parts of a user, a table of users by role. Writing each by hand means that changing the user type requires changing them all. Utility types are built-in generics that derive one type from another, so the variations follow the original automatically.

How it works

Three utilities change every property of an object type:

  • Partial<T> makes every property optional. It describes updates and option objects, where callers give only what they change.
  • Required<T> makes every property required, for example after defaults have been filled in.
  • Readonly<T> makes every property readonly, for values that must not be changed.

Two build a new object type from some properties. Pick<Task, "id" | "title"> keeps only the named properties, and Omit<Task, "id"> keeps all the others. Combinations are common: Partial<Omit<Task, "id">> is "any of the task's fields except its id", the exact type of an update.

Record<K, V> is an object type whose keys are K and values V. With a literal union as the keys, such as Record<Priority, number>, TypeScript insists on an entry for every member, so adding a priority later shows every table that needs updating.

Three work on unions. Exclude<U, X> removes the members assignable to X: Exclude<Priority, "urgent"> is the three calm priorities. Extract<U, X> keeps them instead. NonNullable<T> removes null and undefined.

Two read function types. ReturnType<typeof summary> is the type that summary returns, and Parameters<typeof f> is a tuple of its parameter types. They are handy when a library gives you a function but does not export the types it uses. Note typeof, which turns the value summary into its type.

Example

// Utility types build new types from existing ones.
interface Task {
  id: number;
  title: string;
  done: boolean;
  due?: string;
}

type TaskChanges = Partial<Omit<Task, "id">>; // every field but id, all optional
type TaskSummary = Pick<Task, "id" | "title">;
type Priority = "low" | "normal" | "high" | "urgent";
type Calm = Exclude<Priority, "urgent">;

function update(task: Readonly<Task>, changes: TaskChanges): Task {
  return { ...task, ...changes };
}

function summary(t: Task): TaskSummary {
  return { id: t.id, title: t.title };
}

const counts: Record<Priority, number> = { low: 0, normal: 2, high: 1, urgent: 0 };
const t1: Task = { id: 1, title: "Write report", done: false };
const t2 = update(t1, { done: true, due: "Friday" });
const s: ReturnType<typeof summary> = summary(t2);
const level: Calm = "high";
console.log(t2);
console.log(s, level, counts);
Open in compiler

Line by line

  1. TaskChanges is every task field except id, each optional: a valid update.
  2. TaskSummary keeps only id and title.
  3. Calm is the union of priorities without "urgent".
  4. update takes a Readonly<Task>, so it cannot change its argument; it returns a new task.
  5. counts must have all four priorities, because its type is Record<Priority, number>.
  6. s is typed from summary's return type.

Expected result

{ id: 1, title: 'Write report', done: true, due: 'Friday' }
{ id: 1, title: 'Write report' } high { low: 0, normal: 2, high: 1, urgent: 0 }

In the real world

APIs use Partial for PATCH requests, Omit to remove passwords and internal fields before sending a user to the browser, and Pick to describe list views that need only a few columns. Form libraries type their state as Record<keyof Fields, string> for errors. Many codebases define one main type per entity and derive every other shape from it with utility types.

Common mistakes

  • Copying an interface by hand to remove one field, instead of using Omit.
  • Using Partial where only some fields are optional, which allows empty objects that should be invalid.
  • Forgetting typeof with ReturnType: ReturnType<summary> is an error, because summary is a value.
  • Expecting Readonly to be deep: nested objects can still be changed.

Best practices

  • Keep one source type per entity and derive the rest.
  • Use Record with a literal union when every member needs an entry.
  • Name derived types (type TaskChanges = ...) when they are used in more than one place.

Summary

Utility types derive new types from existing ones: Partial, Required and Readonly change every property; Pick, Omit and Record build object types; Exclude, Extract and NonNullable filter unions; and ReturnType and Parameters read function types. Deriving keeps all the variations in step with the original.

Quick check

1. Which type means 'any of User's fields except id, all optional'?
2. What is Exclude<'a' | 'b' | 'c', 'b'>?
3. Why use Record<Priority, number> instead of { [k: string]: number }?
4. How do you get the return type of a function value f?

Key takeaways

  • Derive related types from one source type instead of writing near-copies by hand.
  • Partial and Omit together describe updates; Pick and Omit describe views of an object.
  • Record with a literal union as keys forces an entry for every member.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.