TypeScript Discriminated Unions and Type Narrowing
On this page
Learning Objective
Model values that can be one of several shapes with union types, narrow them safely with typeof, in, instanceof, equality and custom type guards, represent UI and request state with discriminated unions so impossible states cannot be expressed, and use exhaustive checks so new cases are never forgotten.
Concept Explanation
A union type says a value is one of several types: string or number, a Circle or a Square, "idle" or "loading". Unions model real data well, because frontend code constantly deals with values that vary: an API that returns data or an error, a form field that may be empty, an event that can come from a mouse or a keyboard. Before you can use a union value, you must narrow it, proving to the compiler which member you have.
TypeScript understands the checks you already write. typeof x === 'string' narrows to string, Array.isArray narrows to an array, instanceof narrows to a class, the in operator narrows to the union members that have a property, and comparing with null or a literal value narrows too. Narrowing follows control flow: after an early return for the null case, the rest of the function knows the value is not null. When a check is too complex for the compiler to follow, a user-defined type guard, a function returning x is Type, packages the check for reuse, though the compiler trusts its implementation, so it must be correct.
Discriminated unions are the most valuable pattern built on this. Each member of the union has a common property with a different literal value, the discriminant, such as status: 'loading' or status: 'success'. Checking that property narrows the whole object, so in the success branch the compiler knows data exists and in the error branch it knows error exists. This is how you make impossible states unrepresentable. A request state modeled with separate booleans, isLoading, isError and data, allows contradictions such as loading and error at once, or success without data. A discriminated union only allows the states that can actually happen.
Exhaustiveness checking completes the pattern. In a switch over the discriminant, a default branch that assigns the value to a variable of type never compiles only if every case has been handled. When someone later adds a new status, every switch that does not handle it fails to compile, pointing at each place that needs updating. The satisfies operator and literal types with as const help keep these unions precise.
The same approach applies across the frontend: actions in a reducer, events in an analytics layer, steps in a checkout wizard, message types from a WebSocket and variants of a component's props. A button whose props are either a link with href or a button with onClick, but never both, is a discriminated union too.
| Narrowing technique | Example | Narrows to |
|---|---|---|
| typeof | typeof v === 'string' | Primitive types |
| Truthiness or null check | if (user == null) return | Excludes null and undefined |
| instanceof | err instanceof ApiError | A class |
| in operator | 'href' in props | Members that have the property |
| Literal equality | state.status === 'error' | One union member |
| Type guard function | function isUser(x): x is User | Custom checks, trusted by the compiler |
| never in default | const check: never = state | Fails if a case is missing |
Worked Example: Request State and an Exhaustive Renderer
The boolean version allows impossible combinations. The discriminated union makes each state carry exactly the data it needs, and the renderer must handle every state.
// Before: 2 x 2 x 2 combinations, several of them impossible
interface LoadStateBad<T> { isLoading: boolean; error?: Error; data?: T }
// After: only real states exist
type RemoteData<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; error: Error; retry: () => void }
| { status: 'success'; data: T; refreshedAt: Date };
interface Order { id: string; total: number }
function render(state: RemoteData<Order[]>): string {
switch (state.status) {
case 'idle': return 'Choose a date range';
case 'loading': return 'Loading orders...';
case 'error': return `Could not load orders: ${state.error.message}`; // error is known here
case 'success': return `${state.data.length} orders`; // data is known here
default: {
const unreachable: never = state; // compile error if a status is not handled
return unreachable;
}
}
}
// Props that are either a link or a button, never both
type ActionProps =
| { kind: 'link'; href: string; label: string }
| { kind: 'button'; onClick: () => void; label: string };
function actionHtml(p: ActionProps) {
return p.kind === 'link'
? `<a href="${encodeURI(p.href)}">${p.label}</a>`
: `<button>${p.label}</button>`;
}
// A type guard for data from outside
function isOrder(x: unknown): x is Order {
return typeof x === 'object' && x !== null
&& typeof (x as Order).id === 'string' && typeof (x as Order).total === 'number';
}Add a status such as 'refreshing' to RemoteData and the compiler immediately flags render, because the default branch now receives a value that is not never. That is the safety net that keeps large codebases consistent.
Real-World Examples
- Redux Toolkit and many state libraries model actions as discriminated unions keyed by a type field, and the TypeScript handbook uses the same pattern, with a kind property on shapes, as its canonical example of narrowing.
- TanStack Query's result type exposes a status field with pending, error and success values, and its documentation recommends checking status rather than separate booleans precisely because the status field narrows data and error correctly in TypeScript.
Review Questions & Answers
A union of object types that share a property, the discriminant, whose value is a different literal in each member, such as status: 'loading' or status: 'error'. Checking the discriminant narrows the value to one member, giving access to the properties only that member has.
Separate fields allow contradictory combinations such as loading with an error, or success without data, and the compiler cannot tell which fields exist in which case. A discriminated union only allows the valid states and lets the compiler know exactly which data exists in each branch.
In the default branch of a switch over the discriminant, the value is assigned to a variable of type never. If all members are handled, the value's type has been narrowed to never and the assignment compiles. If a member is unhandled, its type is not assignable to never, so compilation fails.
The compiler trusts the guard's return type without checking its implementation. If the function's logic is wrong, values are narrowed to a type they do not have, producing the same run-time errors as an unsafe cast. Guards must be written and tested carefully, or generated by a validation library.