Discriminated Unions
As a design pattern, a discriminated union is how you model a closed set of states in TypeScript instead of a class hierarchy or a pile of optional fields. One tag field, one object type per state, one switch.
Detailed Explanation
Object-oriented code often expresses "a value that is one of several kinds" as a base class plus subclasses, or as a single class with optional fields and a type string that nobody checks. In TypeScript the type-native form is a discriminated union. It is the same idea as the fundamentals page, used as an architecture choice.
You reach for this pattern when:
- A result is success or failure (or pending), and the payloads differ.
- A UI is in a finite set of views.
- A message protocol has a finite set of frames (workers, websockets).
- A reducer action list is closed.
You do not reach for a class hierarchy unless you need identity, instanceof, or shared mutable behavior. You do not reach for optional fields (ok?: boolean; data?: T; error?: E) when the combinations are not all legal.
The pattern has three parts you keep together. A union type with a shared literal tag. A function that switches on the tag and returns a single result type. An exhaustiveness check so a new member is a compile error. The fundamentals page shows the mechanics. The design choice is: this union is the public API. Export it. Do not export a class per member unless a member needs methods.
Compared to the visitor pattern on a class hierarchy, a switch on a union is fewer types and no double dispatch. Compared to a strategy pattern with a common interface, a union is better when the data differs and the operations are few; a strategy is better when the behavior differs and the data is shared.
The cost is that adding a state means touching every switch. That is the point. If you have twenty operations on a growing set of states, a class or a map of handlers typed as Record<Tag, Handler> may scale better. You can still type that map as Record<Union["tag"], ...> and keep exhaustiveness.
Do not duplicate this pattern as a second, different model in the same module. If the fundamentals term already lives in your head, the pattern term is the reminder to use it at API boundaries.
Code Examples
1. A public result type — the pattern at an API boundary.
// 1. A public result type — the pattern at an API boundary.
export type LoadState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "ok"; data: T }
| { status: "error"; message: string };
export function label<T>(state: LoadState<T>): string {
switch (state.status) {
case "idle":
return "Idle";
case "loading":
return "Loading";
case "ok":
return "Ready";
case "error":
return state.message;
}
}2. Optional fields are the anti-pattern.
// 2. Optional fields are the anti-pattern.
type Loose<T> = { ok: boolean; data?: T; error?: string };
// { ok: true, error: "nope" } is legal and wrong.3. A handler map still stays exhaustive.
// 3. A handler map still stays exhaustive.
type Tag = LoadState<unknown>["status"];
const handlers: Record<Tag, () => string> = {
idle: () => "Idle",
loading: () => "Loading",
ok: () => "Ready",
error: () => "Error",
};Common Gotchas
A public class hierarchy plus a union for the same states will drift
pick one model per boundary.
Optional-field "unions" allow illegal combinations
if a combination cannot happen, it should be unrepresentable.
The fundamentals page has the narrowing rules
this page is when to choose the pattern.
Twenty switches on the same union is a signal
consider a `Record` of handlers or a real visitor if operations keep growing.