Discriminated unions

Intermediate · 5 min

Modelling data that comes in several shapes as a union of object types sharing a literal tag, so one check narrows the whole object.

Before thistypeof, instanceof, and in narrowingUnion and literal typesObject types, optional and readonly properties

Web Dev Simplified · 5 min

Discriminated unions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • One object type with a status field and a pile of optional properties lets through states that can't happen, like a success with no data, and forces a check on every optional field even after you've checked the status.
  • A discriminated union splits that object into one type per state, each with the same property (the discriminant, or tag) set to a different literal type.
  • Checking the tag with `===` or a `switch` narrows the entire object, so the properties that exist in that state become available without any further checks.
  • The tag has to be a literal type, such as a string literal, number literal, or `true`/`false`; a tag typed as plain `string` can't tell the members apart.
  • Properties that only exist on some members aren't accessible on the union at all, which is the point: you have to narrow before reading them.
  • The `Result` pattern, `{ ok: true; value: T } | { ok: false; error: E }`, uses a boolean tag to return either a value or an error without throwing.

The bag of optional fields

Picture the state of a data fetch. It’s loading, or it succeeded with some data, or it failed with an error message. A first attempt at a type often looks like this:

type RequestState = {
  status: "loading" | "success" | "error";
  data?: string[];
  error?: string;
};

It compiles, and it’s a weak model. Nothing stops { status: "success" } with no data, or { status: "loading", error: "?" }. And checking the status tells TypeScript nothing about the other fields:

function render(s: RequestState) {
  if (s.status === "success") {
    return s.data.length;
    // error: 's.data' is possibly 'undefined'.
  }
}

You know success means data is present. The type doesn’t say so, so the checker can’t know it either.

One type per state

The fix is to describe each state as its own object type, and join them in a union:

type RequestState =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; error: string };

Every member has a status property, and in each one it’s a different string literal. That shared property is the discriminant, or tag. Impossible states are gone: a success without data is now a type error.

Think of it like a shipping label with a box ticked. Once you see “fragile” is ticked, you know which handling rules apply to the whole parcel, not just to that one box.

One check narrows everything

Because each member has its own tag value, checking the tag rules out every member that doesn’t match. The whole object narrows, not just the status field:

function render(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading...";
    case "success":
      return `${state.data.length} items`; // state: { status: "success"; data: string[] }
    case "error":
      return `Failed: ${state.error}`;
  }
}

if (state.status === "success") works the same way. So does destructuring the tag into a const first, const { status } = state;, then checking status. TypeScript tracks that the two are linked.

Before you narrow, the members’ private properties are off limits:

state.data;
// error: Property 'data' does not exist on type 'RequestState'.

That error is the feature. On a union you can only read properties that every member has. The type forces you to find out which state you’re in before reading data that belongs to one state.

What makes a good tag

The tag must be a literal type: a string literal, a number literal, or true/false. If each member declared status: string, every member could match "success", nothing could be ruled out, and no narrowing would happen.

String literals are the usual choice, since they read well in a debugger and in JSON. The property name is up to you; type, kind, and status are all common. What matters is that every member has it and no two members share a value.

The Result pattern

A boolean tag gives you a tidy way to return failure without throwing:

type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: Error };

function parseAge(raw: string): Result<number> {
  const n = Number(raw);
  return Number.isNaN(n)
    ? { ok: false, error: new Error(`Not a number: ${raw}`) }
    : { ok: true, value: n };
}

const result = parseAge("41");
if (result.ok) {
  result.value.toFixed(0); // result: { ok: true; value: number }
} else {
  console.error(result.error.message);
}

A thrown exception never appears in a function’s type, so callers can forget it. A Result puts failure in the return type, and the checker won’t let anyone read value until they’ve checked ok. The <T> is a generic parameter, covered in the generics group; for now, read it as “whatever type the value is”.

About the video

Kyle Cook of Web Dev Simplified starts from the same optional-field problem and rebuilds it as a discriminated union in about five minutes. His examples use React component props, but the mechanics are identical to the request-state example here, and he also covers the cases where the pattern gets awkward. The Andrew Burgess video linked below moves on to the switch statement and leads straight into the next lesson: making the compiler tell you when a switch forgets a member.

Check yourself

  1. 01What can go wrong with `type State = { status: "loading" | "success" | "error"; data?: string[]; error?: string }`?

    The type permits impossible combinations, such as `status: "success"` with no `data` or with an `error`. Checking `status === "success"` also does nothing for `data`, which stays `string[] | undefined`, so you need a second check that the type system should have made unnecessary.

  2. 02How does a discriminated union make `state.data` available after `if (state.status === "success")`?

    Each union member has a different literal type for `status`. The check rules out every member whose `status` isn't `"success"`, so `state` narrows to the one member that declares `data: string[]`, and the property is available as a non-optional `string[]`.

  3. 03Why does `state.data` fail to compile when `state` hasn't been narrowed yet?

    On a union you can only access properties that every member has. `data` exists only on the success member, so reading it from the full union is an error. Narrowing on the tag first is what proves the property is there.

  4. 04Would the narrowing still work if each member declared `status: string` instead of a literal like `"success"`?

    No. If every member's tag is plain `string`, then `status === "success"` is possible for every member, so nothing can be ruled out and the union stays whole. The tag only discriminates because each member's literal type excludes the others.

  5. 05Why might a function return `{ ok: true; value: number } | { ok: false; error: Error }` instead of throwing on failure?

    The failure case becomes part of the return type, so callers can't read `value` without checking `ok` first, and the compiler enforces that. A thrown error appears nowhere in a function's type, so forgetting to handle it is invisible until runtime.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark