Discriminated unions give TypeScript a reliable way to represent mutually exclusive states, from API results and loading screens to form workflows and domain events. This guide compares them with optional-property objects, enums, and classes, then shows reusable patterns for narrowing, state transitions, exhaustive checks, and safely adding new variants.
Overview
A discriminated union is a union of object types that share a property with different literal values. That shared property, usually called a kind, status, or type, tells TypeScript which member of the union is currently available.
type RequestState<T> =
| { status: 'idle' }
| { status: 'loading'; startedAt: number }
| { status: 'success'; data: T }
| { status: 'error'; message: string };Each state has the data that belongs to it and excludes data that does not. A successful request has data; an error has message; an idle request has neither. This is more precise than one object with several optional properties, where invalid combinations can be represented accidentally.
The pattern is especially useful when a value must be one of several complete alternatives. It works well in React component state, Node.js service results, reducers, parsers, validation outcomes, payment workflows, and event-driven code. For broader guidance on narrowing and compiler diagnostics, see the TypeScript type narrowing and error fixes guide.
Comparison at a glance
| Model | Strength | Main risk or limitation | Best use |
|---|---|---|---|
| Optional-property object | Simple to start and easy to serialize | Allows contradictory or incomplete combinations | Truly independent optional fields |
| Discriminated union | Encodes valid alternatives and supports automatic narrowing | Requires an explicit variant design | Mutually exclusive states and workflows |
| Enum | Provides a named set of values | Describes labels, not the complete data for each case | Stable status or category values |
| Class-based model | Can combine data with behavior and invariants | More runtime structure and serialization considerations | Rich domain objects with methods |
How to compare options
Start by asking whether the alternatives are mutually exclusive. If a result cannot be both successful and failed at the same time, a discriminated union usually expresses that rule more directly than optional properties. If fields can independently appear together, an ordinary object may be the clearer model.
Next, separate the label from the payload. An enum or string union can answer “which category is this?” but it does not, by itself, require the data associated with that category. A discriminated union combines both:
type PaymentResult =
| { type: 'approved'; authorizationCode: string }
| { type: 'declined'; reason: string }
| { type: 'pending'; reference: string };Then evaluate how the value is created, transported, and consumed. Plain unions are convenient at module boundaries and in JSON-shaped API data. Classes may be appropriate when callers need methods, private state, or runtime validation, but they require more care when values cross a JSON boundary.
Finally, consider what should happen when a new alternative is introduced. A good model makes incomplete handling visible. With strict compiler settings, an exhaustive check can turn a forgotten UI branch or event handler into a compile-time error. Review the project’s strictness settings in the strict tsconfig guide before relying on that feedback.
Feature-by-feature breakdown
1. Optional properties versus mutually exclusive states
This shape looks flexible but is weakly constrained:
type LooseResult = {
loading?: boolean;
data?: string;
error?: string;
};It permits no fields, all fields, or contradictory combinations. A discriminated union makes the valid cases explicit:
type Result =
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: string };TypeScript can now narrow the payload after checking status:
function messageFor(result: Result): string {
if (result.status === 'loading') return 'Loading';
if (result.status === 'success') return result.data;
return result.error;
}2. String unions and enums
A string union is often enough when you need only a finite set of labels:
type Status = 'idle' | 'loading' | 'complete';Enums can be useful when a shared named value set is part of an existing API or domain convention. However, an enum does not connect each value to a different payload. If the data changes with the status, a discriminated union is usually the more complete representation.
3. Exhaustive switch checks
A reusable never helper verifies that every variant was handled:
function assertNever(value: never): never {
throw new Error('Unhandled variant: ' + JSON.stringify(value));
}
function renderResult(result: Result): string {
switch (result.status) {
case 'loading':
return 'Loading';
case 'success':
return 'Data: ' + result.data;
case 'error':
return 'Error: ' + result.error;
default:
return assertNever(result);
}
}If you add { status: 'cancelled' } to Result without adding a switch branch, the value reaching assertNever is no longer never, so the compiler reports the missing case. This is one of the most practical TypeScript exhaustive switch patterns for long-lived codebases.
4. State transitions
A union describes states; a transition function describes which changes are allowed. Keeping transitions explicit prevents callers from assigning arbitrary next states:
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; message: string };
type Event =
| { type: 'start' }
| { type: 'resolve'; data: string }
| { type: 'reject'; message: string }
| { type: 'reset' };
function transition(state: State, event: Event): State {
switch (event.type) {
case 'start':
return { status: 'loading' };
case 'resolve':
return { status: 'success', data: event.data };
case 'reject':
return { status: 'error', message: event.message };
case 'reset':
return { status: 'idle' };
default:
return assertNever(event);
}
}For stricter business rules, narrow both the current state and event before returning. For example, a resolve event might be valid only while loading. The type system can document that rule, while runtime checks remain necessary for untrusted input.
5. Adding a new variant safely
When adding a variant, update the union first, then let compiler errors identify affected consumers. Search for switches on the discriminant, lookup maps keyed by the union, serializers, tests, and UI renderers. Add the new payload fields, define its legal transitions, and test both the new path and existing paths.
Do not assume that TypeScript validates external JSON automatically. Parse and validate API data at the boundary before treating it as a trusted union. When generated API types are involved, compare the generation workflow and validation responsibilities in the TypeScript API client generation guide.
Best fit by scenario
- UI loading and error states: Use a discriminated union when the component should render different payloads for loading, success, empty, and error cases. React-specific examples can build on these React TypeScript patterns.
- API results: Model success and failure separately, but validate the response at the network boundary. This prevents a compile-time type from being mistaken for runtime validation.
- Reducers and workflows: Use a state union plus an event union. Exhaustive reducers make new workflow branches visible during development.
- Domain events: Use a stable event discriminant and event-specific payloads. Keep event names and payload shapes compatible with the system’s serialization requirements.
- Simple categories: Prefer a string union or enum when all cases share the same data shape and no case-specific payload is needed.
- Behavior-rich objects: Consider classes when invariants and methods are central, but use unions when the primary need is transparent data modeling and control-flow narrowing.
For module boundaries, export the union and its constructors or factory functions deliberately rather than exposing incidental internal states. The guide to TypeScript module boundaries covers related public API decisions.
When to revisit
Revisit a discriminated union whenever a new API response shape, UI state, domain event, or workflow branch is introduced. Treat compiler errors from exhaustive checks as a change-management checklist rather than suppressing them with a broad cast.
During maintenance, check five things:
- Does every variant have a clear discriminant and only the payload it needs?
- Are external values validated before they enter the trusted union?
- Do switches, renderers, serializers, and lookup tables handle every case?
- Do state transitions reject impossible combinations rather than silently accepting them?
- Do tests cover both the new variant and the behavior of unaffected variants?
Return to this comparison when the project adopts a new framework, API generation workflow, compiler configuration, or runtime validation library. The surrounding tools may change, but the design question remains stable: can the type make invalid states difficult to represent, and can the compiler point to every place that needs attention when the model evolves?