Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 96 ยท Narrowing

Discriminated Unions

Model data safely with TypeScript discriminated unions - tag properties, switch narrowing, exhaustiveness checks with never, loading states and Result types.

A discriminated union (also called a tagged union) is a union of object types that all share one property, the discriminant or tag, whose value is a different literal type in each member. Check the tag, and TypeScript instantly knows which member you have and which other properties exist. It's the single most useful pattern in everyday TypeScript.

Why does it matter so much? Because real data comes in shapes: a payment is by card or by bank transfer, a network request is loading, done or failed, a shape is a circle or a rectangle. Each shape has its own fields. Discriminated unions let you write those shapes down exactly, make impossible combinations impossible to build, and get a compile error whenever you forget to handle a case. This lesson builds on Narrowing.

Your first tagged union

Here are two shapes. Both have a kind property, and its type is a different string literal in each:

TypeScript Switching on the tag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Three ingredients make this work:

  1. A common property (kind) present in every member of the union.
  2. Literal types for that property ('circle', 'rectangle'), each unique to one member.
  3. A check on the property (switch, if, ===), which TypeScript uses to narrow the whole object.

Reading shape.kind is always allowed, because every member has it. Reading shape.radius before the check is not, because a Rectangle has no radius. Inside case 'circle', though, TypeScript has removed Rectangle from the union, so shape.radius is fine.

The tag doesn't have to be called kind. type, status, tag and ok are all common. It doesn't even have to be a string: number literals, booleans, null and undefined work too, as long as each member's tag type is a literal (or a union of literals).

Why not optional properties?

Without a discriminant, people often reach for one object type with lots of optional properties. Compare the two designs for a request's state:

TypeScript
// One loose type: every combination is allowed
interface LooseState {
  loading: boolean;
  data?: string[];
  error?: string;
}

// A discriminated union: only real states exist
type RequestState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string[] }
  | { status: 'error'; error: string };

LooseState happily accepts { loading: true, data: [...], error: 'Timeout' }. Is that loading, done or failed? Nobody knows, and every function that reads it has to guess. With RequestState, that object can't even be written: a 'loading' state has no data property, and a 'success' state must have data. Errors that used to appear at runtime now appear while you type.

TypeScript Impossible states are compile errors (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both lines fail, and nothing runs. The first is error TS2322 because a success state is missing data: Property 'data' is missing in type '{ status: "success"; }' but required in type '{ status: "success"; data: string[]; }'. The second is error TS2353, an excess property check: Object literal may only specify known properties, and 'data' does not exist in type '{ status: "loading"; }'. Notice how TypeScript used the tag to pick the right member before comparing the rest.

Modelling state: loading, success, error

Here's that request state in a realistic function that renders a message for each case. The if chain works exactly like a switch:

TypeScript Rendering every state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

After three returns, control-flow analysis knows only { status: 'success'; data: string[] } remains, so state.data is allowed without any check. Each state carries exactly the data that makes sense for it: a start time while loading, a message and a retry flag on error.

You can also narrow with destructuring, as long as you destructure into const variables and check the tag variable. After const { status } = state;, the check if (status === 'error') narrows state too, so state.error is allowed. And since TypeScript 4.6, properties destructured together with the tag are narrowed as well: in const { kind, payload } = action;, checking kind also narrows payload.

Exhaustiveness checking with never

The biggest payoff comes when your union grows. Suppose you add a Triangle to Shape. Every switch on shape.kind should now handle it, and you want the compiler to find every place you forgot.

The trick uses never, the type with no values. After all cases are handled, the narrowed type of shape is never. If a case is missing, it's that missing member instead. Assign it to a never variable in the default branch, and a missing case becomes a compile error:

TypeScript An exhaustive switch with assertNever

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This compiles because all three kinds are handled, so shape is never in default. Now delete the triangle case (or add a fourth shape) and see what happens:

TypeScript A forgotten case (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error points straight at the problem: main.ts(17,26): error TS2345: Argument of type '{ kind: "triangle"; base: number; height: number; }' is not assignable to parameter of type 'never'. It even names the member you forgot.

Why have assertNever throw, if the compiler already proves the code is unreachable? Because types are erased and data can lie. A value parsed from JSON or sent by an older server might have kind: 'hexagon'. Throwing a clear error at runtime is far better than silently returning undefined.

If you don't want a helper, the shortest form is a const in the default branch: const unreachable: never = shape;. It catches the same mistakes at compile time. Another option is the switch without default plus an explicit return type, which gives error TS2366 when a case is missing, but its message doesn't say which case.

A Result type instead of exceptions

Discriminated unions are perfect for functions that can fail in expected ways. Instead of throwing, return a value that says whether it worked. A popular shape uses a boolean tag called ok:

TypeScript A Result type with an ok tag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The Result<T, E> type is a generic type alias: T is the success value, E the error (a string by default). Callers can't read result.value without checking result.ok first, which is exactly the discipline you want. With exceptions, nothing in the type tells a caller that a function can fail. Error Handling compares the two approaches in detail.

Unions of events and actions

Another classic use is describing messages: events in a game, commands in a CLI, or actions in a state reducer. Each message has a type tag and its own payload, and one function handles them all:

TypeScript A typed reducer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This is the pattern behind Redux-style reducers and many state machines (you'll build one in the State Machine project). Adding a new action means adding one member to CartAction, and the never check in default tells you where to handle it. The braces after default: give the const its own block scope, which is a good habit inside switch.

Narrowing pitfalls

A few things stop TypeScript from discriminating:

  • The tag isn't a literal type. If one member has kind: string, checking kind === 'circle' can't rule it out. Keep tags literal; when you build objects in a variable first, use an annotation or as const so 'circle' isn't widened to string (see Literal Types and as const).
  • Checking a copy of the tag in a let. Narrowing through an alias only works when the alias is a const (or a parameter that is never reassigned).
  • Destructuring the payload first. const { kind, radius } = shape fails before the check, because radius doesn't exist on every member. Narrow first, then destructure.
  • Overlapping tags. If two members share a tag value, checking it narrows to both of them. That can be fine (it's how you group cases), but it's usually a design smell.

You can also discriminate with several properties or with in when a third-party type has no tag, but a single literal tag is clearest. If you control the type, add one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes { kind: 'a'; x: number } | { kind: 'b'; y: string } a discriminated union?

    The discriminant is a shared property with a unique literal type per member. Checking it tells TypeScript which member you have.
  2. 2. type R = { ok: true; value: number } | { ok: false; error: string }. Inside if (!r.ok) { ... }, what can you read?

    !r.ok means ok is false, which narrows r to the error member. value doesn't exist there.
  3. 3. In an exhaustive switch, what is the type of the value in the default branch when every case is handled?

    Each case removes one member. With none left, the type is never, which is why assigning it to a never variable compiles.
  4. 4. You add { kind: 'hexagon'; side: number } to a Shape union, and a function uses default: return assertNever(shape);. What happens?

    The unhandled member reaches default, so its type is passed where never is required. That's error TS2345 at compile time.
  5. 5. Why is { status: 'loading' } | { status: 'success'; data: string[] } better than { loading: boolean; data?: string[] }?

    The union describes only the states that really exist, and each one requires exactly its own data, so invalid objects fail to compile.

Summary

  • A discriminated union is a union of object types sharing a tag property with a unique literal type per member, e.g. kind: 'circle' | 'rectangle'.
  • Checking the tag with switch, if or === narrows the whole object, unlocking that member's properties.
  • Unions model states precisely and make impossible states unrepresentable, unlike one type full of optional properties.
  • Exhaustiveness checking: in default, assign the value to never (or call assertNever) so a forgotten case is a compile error that names the missing member.
  • Result<T, E> with an ok tag is a clean way to return expected failures; tagged actions or events power reducers and state machines.
  • Keep tags literal, narrow before destructuring, and avoid duplicate tag values.

Next: Custom Type Guards