Type-Safe State Machines with TypeScript Discriminated Unions and Exhaustive Pattern Matching
How to model complex asynchronous workflows, eliminate invalid application states at compile time, and enforce exhaustive handling using the never type.
Discriminated unions (tagged unions) are one of TypeScript’s most potent features for domain modeling. By assigning a shared literal property across distinct object interfaces, TypeScript enables automatic control flow narrowing. When paired with the bottom type `never`, developers can construct mathematical finite state machines where illegal combinations of status, loading states, and error messages are impossible to represent.
THE PRODUCTION PROBLEM STATEMENT
In typical frontend applications, developers often manage state with multiple independent booleans: isLoading, isError, isSuccess, and data. This allows impossible states like { isLoading: true, isError: true, data: user }, leading to UI glitches, conflicting visual states, and unpredictable edge cases.
How Do Tagged Unions Make Illegal States Impossible?
Instead of modeling attributes independently, a discriminated union models the entire system as a finite set of mutually exclusive states. A shared literal property-such as "status"-acts as the discriminant tag.
When code branches on state.status === "success", TypeScript narrows the type in that block, guaranteeing that state.data exists and state.error does not.
export type AsyncState<T> =
| { status: 'idle' }
| { status: 'pending' }
| { status: 'success'; data: T; receivedAt: number }
| { status: 'error'; error: Error; retryCount: number };
// Exhaustive matching helper
export function assertNever(x: never): never {
throw new Error(`Unexpected object in exhaustive check: ${JSON.stringify(x)}`);
}
export function renderAsyncView<T>(state: AsyncState<T>): string {
switch (state.status) {
case 'idle':
return 'System standing by.';
case 'pending':
return 'Synchronizing with remote cluster...';
case 'success':
// TypeScript guarantees state.data exists!
return `Loaded at ${state.receivedAt}: ${JSON.stringify(state.data)}`;
case 'error':
// TypeScript guarantees state.error and retryCount exist!
return `Failed (Attempt ${state.retryCount}): ${state.error.message}`;
default:
// If a new status is added to AsyncState, TypeScript fails compilation here!
return assertNever(state);
}
}How to Enforce Legal State Transitions at Compile Time?
State transitions can be restricted so an application cannot jump directly from "idle" to "success" without passing through "pending".
By defining transition functions that only accept specific source states, TypeScript flags invalid state jumps as compile-time type mismatches.
// Anti-Pattern: Allows impossible conflicting states
interface QueryState<T> {
isLoading: boolean;
isError: boolean;
error: Error | null;
data: T | null;
}// Recommended: Only valid states can exist
type QueryState<T> =
| { status: 'loading' }
| { status: 'error'; error: Error }
| { status: 'success'; data: T };[PROBABLE CAUSE] A new status variant was added to the discriminated union but the switch statement forgot to handle that case.
[VERIFIED RESOLUTION] Add a new case branch for the missing variant before the default assertNever call.
case 'newVariant': return handleVariant(state);Frequently Asked Questions & Technical Inquiries
Direct, practical answers to common architectural and debugging questions.
Any property with literal types (strings, numbers, booleans). Common choices are "type", "kind", "status", and "tag".
Faisal Askari
Verified AuthorSoftware Engineer & Full-Stack Developer
Faisal Askari is a software engineer with deep expertise in web systems architecture, the JavaScript runtime ecosystem, and client-side performance engineering. Over years of hands-on production engineering, he has designed and shipped enterprise dashboards, high-converting digital interfaces, and specialized full-stack applications.
Enterprise TypeScript System Architecture
Need an architectural overhaul to eliminate runtime state bugs and introduce strict compile-time domain models?
Mastering Advanced TypeScript: Discriminated Unions, Type Narrowing, and Conditional Inference
A practical guide to building zero-runtime-cost type architectures using distributive conditional types, template literals, custom type guards, and exhaustive pattern matching.
TypeScript satisfies Operator vs Type Annotations: Preserving Literal Types and Narrow Contracts
A practical deep dive into bottom-up validation, preventing type widening, and retaining exact autocompletion across configuration objects.