All academies
Roadmap/Advanced

Level 13

Utility Types

TypeScript ships a standard library of type transformers — Partial, Pick, Omit, Record, ReturnType, and friends — that let you derive new types from existing ones instead of duplicating shape definitions.

20 min read + quiz

Derive, Don't Duplicate

The core philosophy behind utility types is single source of truth. If you have a User interface, the shape of 'a partial update to a user' or 'a user without server-managed fields' should be computed from User, not maintained by hand. Hand-copied types silently drift apart when someone adds a field.

Every utility type is just a mapped or conditional type with a name — you saw the machinery in the previous lesson. Knowing they are ordinary types demystifies them: you can read their one-line definitions by hovering in your editor, and you can write your own in the same style.

A good rule of thumb: when you find yourself writing a second interface that is 'the same as X but with some fields different', stop and reach for Partial, Pick, Omit, or an intersection with Omit instead.

interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

// Derived, never drifts out of sync with User:
type UserUpdate = Partial<Omit<User, "id" | "createdAt">>;

const patch: UserUpdate = { name: "Grace" }; // any subset of editable fields

Compose utilities to express 'editable subset of User'.

Partial, Required, and Readonly

Partial<T> makes every property optional and is the natural type for update payloads, configuration overrides, and builder-style APIs. Required<T> is its inverse, stripping optionality — useful after you have filled in defaults and want the compiler to know everything is present.

Readonly<T> marks every property readonly, preventing assignment after construction. This is compile-time only; it does not freeze the object at runtime (that is Object.freeze). Still, it documents and enforces intent throughout the codebase for free.

Note all three are shallow. Partial<T> makes top-level properties optional, but a nested object property, when present, must still be complete. If you need deep variants you must write a recursive mapped type or pull in a utility library — and think twice, because deep partials make it hard to know what is actually filled in.

interface Config {
  host: string;
  port: number;
  tls: { cert: string; key: string };
}

function withDefaults(overrides: Partial<Config>): Config {
  return {
    host: "localhost",
    port: 8080,
    tls: { cert: "", key: "" },
    ...overrides,
  };
}

const cfg: Readonly<Config> = withDefaults({ port: 3000 });
// cfg.port = 9999; // Error: cannot assign to readonly property

Partial for inputs with defaults, Readonly for the result.

Pick, Omit, and Record

Pick<T, K> selects a subset of properties by key; Omit<T, K> removes them. Use Pick when the subset is small and stable ('just the display fields'), and Omit when you want 'everything except' semantics ('all fields except the password hash'). They express intent in opposite directions, so choose the one that keeps working when T gains new fields.

One subtlety: Omit's key parameter is not constrained to keyof T, so a typo in the omitted key fails silently — Omit<User, 'emial'> omits nothing and reports no error. If you want strictness, write your own StrictOmit with K extends keyof T.

Record<K, V> builds an object type from a key union and a value type. Record<'draft' | 'published', number> guarantees both keys exist with number values — the compiler will error if you forget one, which makes Record excellent for exhaustive lookup tables keyed by a union.

interface Article {
  id: string;
  title: string;
  body: string;
  authorId: string;
  passwordProtected: boolean;
}

type ArticlePreview = Pick<Article, "id" | "title">;
type PublicArticle = Omit<Article, "passwordProtected">;

type Status = "draft" | "review" | "published";
const statusLabels: Record<Status, string> = {
  draft: "Draft",
  review: "In review",
  published: "Live",
  // Missing a key? Compile error. Extra key? Also an error.
};

Record enforces exhaustive lookup tables over a union.

Function Utilities: ReturnType, Parameters, Awaited

ReturnType<T> and Parameters<T> extract a function's return and parameter types. They are indispensable when a library exports a function but not the types it uses — you can recover those types without asking the maintainer to export them.

The typeof operator (in type position) pairs with these constantly: ReturnType<typeof createStore> gives you the store type without ever naming it. This pattern is everywhere in Redux and React Query codebases.

Awaited<T> recursively unwraps promises: Awaited<Promise<Promise<string>>> is string. It models what await actually does, including nested thenables, and is what the standard library uses to type Promise.all correctly.

function createStore(initial: number) {
  let value = initial;
  return {
    get: () => value,
    set: (next: number) => {
      value = next;
    },
  };
}

type Store = ReturnType<typeof createStore>;
// { get: () => number; set: (next: number) => void }

type SetArgs = Parameters<Store["set"]>; // [next: number]

async function loadCount(): Promise<number> {
  return 42;
}
type Count = Awaited<ReturnType<typeof loadCount>>; // number

Recover types from values you did not define.

Union Utilities and When to Write Your Own

Exclude<T, U> removes members from a union and Extract<T, U> keeps only matching members. NonNullable<T> is Exclude specialized for null and undefined. These operate on unions the way Pick and Omit operate on object keys.

These utilities compose well: Extract<Shape, { kind: 'circle' }> pulls one variant out of a discriminated union, which beats maintaining a separate Circle alias that can drift from the union definition.

Write a custom utility type when you use the same composition three or more times. Something like type EditableFields<T> = Partial<Omit<T, 'id' | 'createdAt'>> centralizes a project convention. Name it by intent, not mechanics — EditableFields says more than PartialOmitIdCreatedAt ever could.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "line"; length: number };

type Drawable = Exclude<Shape, { kind: "line" }>;
// circle | square

type Circle = Extract<Shape, { kind: "circle" }>;
// { kind: "circle"; radius: number }

type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // string

Exclude and Extract filter unions by assignability.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

You need a type for PATCH request bodies that may include any subset of a User's editable fields, but never id. Which composition fits best?

Question 2 · True or false

Partial<T> makes properties optional at every level of nesting, including nested objects.

Question 3 · Find the error

The developer intends to hide the password from this type, but the code has a silent bug. What is it?

interface Account {
  username: string;
  password: string;
}

type SafeAccount = Omit<Account, "pasword">;

Question 4 · Predict the output

What does this program print?

const labels: Record<"a" | "b", string> = { a: "Alpha", b: "Beta" };
const keys = Object.keys(labels);
console.log(keys.length, labels.a);

Question 5 · Multiple choice

A library exports createClient but not its return type. How do you name that type in your own code?