Discriminated unions — also called tagged unions — are the most reliable tool I have found for making illegal states unrepresentable in TypeScript. When your domain has several mutually exclusive shapes that share a common concept, like a payment that can be a credit card, bank transfer, or crypto settlement, a naive approach of optional fields and boolean flags quickly collapses under its own weight. I have inherited codebases where a single Payment interface had seven optional properties and three boolean flags like isCard and isProcessed, and every function began with a tangle of defensive checks. Discriminated unions replace that ambiguity with a single literal property that tells both you and the compiler exactly which variant you are handling. The result is code that is safer to change, easier to test, and self-documenting at the type level, without any runtime cost.
Anatomy of a Discriminant: How TypeScript Narrows Unions Without Runtime Overhead
A discriminated union in TypeScript has three strict requirements that the compiler uses for control-flow narrowing. First, every member of the union must be an object type. Second, every member must share a common property — the discriminant. Third, the type of that discriminant property must be a literal type, typically a string literal, and must be unique across members. When those conditions are met, checking the discriminant narrows the entire union to a single member. According to MDN Web Docs on type narrowing, this pattern leverages TypeScript's control flow analysis rather than emitting any extra JavaScript.
In my experience, the choice of discriminant name matters more than it seems. I standardize on kind or type for domain entities and status for state machines, and I never reuse type if the union will be serialized to an external system that already reserves that field. The literal values themselves should describe the domain, not the implementation. Prefer kind: "refund" over kind: "refundObjectType2". I have also found that keeping the discriminant as a required, readonly property prevents a subtle class of bugs where object spreads or defaults accidentally overwrite it.
Why Literal Discriminants Beat Booleans and Optional Fields
Boolean flags do not scale. Two booleans create four combinations, three create eight, and most of those combinations are invalid in your domain. Optional fields are worse because they conflate “not applicable” with “not yet loaded.” A discriminated union forces you to enumerate only the valid shapes. The compiler then enforces that every consumer handles each shape explicitly, and autocomplete will suggest only the properties that exist for the narrowed variant. This is not just a style preference — it fundamentally changes how refactors propagate. When I add a new payment method, every switch on kind that lacks a case for it becomes a compile error if exhaustiveness is configured correctly.
// A domain model where illegal states are unrepresentable
type CreditCardPayment = {
readonly kind: "creditCard";
readonly cardNumber: string;
readonly expiry: string;
readonly cvv: string;
readonly amountCents: number;
};
type BankTransferPayment = {
readonly kind: "bankTransfer";
readonly iban: string;
readonly bic: string;
readonly amountCents: number;
readonly reference: string;
};
type CryptoPayment = {
readonly kind: "crypto";
readonly walletAddress: string;
readonly network: "ethereum" | "bitcoin" | "solana";
readonly amountCents: number;
readonly txHash?: string;
};
type Payment = CreditCardPayment | BankTransferPayment | CryptoPayment;
function getPaymentDescriptor(payment: Payment): string {
switch (payment.kind) {
case "creditCard":
return `Card ending in ${payment.cardNumber.slice(-4)}`;
case "bankTransfer":
return `Transfer ${payment.reference} to ${payment.iban}`;
case "crypto":
return `Crypto via ${payment.network} to ${payment.walletAddress}`;
}
}
Notice what this model prevents: you cannot construct a Payment that has both an iban and a cardNumber, and you cannot access payment.bic without first proving payment.kind === "bankTransfer". If you try, TypeScript will reject it. For teams working with complex utilities, combining this pattern with TypeScript Utility Types: Pick, Omit, Partial and Record Explained lets you derive narrowed views, such as creating input types with Omit<CryptoPayment, "txHash"> while keeping the discriminant intact.
Exhaustiveness Checking That Actually Fails Your Build When You Miss a Case
Narrowing alone is insufficient if you can silently forget a branch. The real power of discriminated unions comes from exhaustiveness checking — a technique that turns an unhandled variant into a type error. I've found that teams who skip this step eventually regress to the same class of bugs they were trying to escape, because a new union member gets handled in one place and ignored in ten others.
The classic approach uses a helper that asserts a value is of type never. In a switch or if-else chain, after handling all known discriminants, the remaining type should be never. If you missed a case, the remaining type is not never, and the assignment fails. I enforce this with strict mode and noUnusedLocals disabled for this one pattern, and I keep the helper in a shared assert.ts module so it cannot be locally silenced.
Implementing the Never Assertion Without Type Casts
There are two reliable ways to trigger the error. The first is an assertNever function that takes a never parameter and throws. The second is assigning the unhandled value to a variable typed as never directly in the default branch. Both work, but I prefer the function because it produces a clearer error message and guarantees a runtime exception if the check is somehow bypassed in JavaScript that circumvents the type system. In my experience, you should never use as never or as unknown to silence this error — that defeats the entire purpose.
function assertNever(value: never): never {
throw new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);
}
type RefundState =
| { readonly status: "pending"; readonly requestedAt: string }
| { readonly status: "approved"; readonly approvedBy: string; readonly approvedAt: string }
| { readonly status: "rejected"; readonly reason: string; readonly rejectedAt: string }
| { readonly status: "settled"; readonly settlementId: string; readonly settledAt: string };
function getRefundLabel(state: RefundState): string {
switch (state.status) {
case "pending":
return `Pending since ${state.requestedAt}`;
case "approved":
return `Approved by ${state.approvedBy}`;
case "rejected":
return `Rejected: ${state.reason}`;
case "settled":
return `Settled ${state.settlementId}`;
default:
return assertNever(state);
}
}
// If you add { status: "reversed" } to RefundState, this function will not compile
// until you handle it. That is the guarantee you want.
This pattern becomes non-negotiable as a domain grows. I have used it for order lifecycles with over a dozen states, and the compiler became the most reliable reviewer on the team. When migrating a large codebase to this style, the guidance in Migrating to TypeScript Strict Mode: A Step-by-Step Approach is directly applicable — enabling strictNullChecks and strict first surfaces the places where non-exhaustive checks are hiding undefined access.
Modeling Async State Machines With Discriminated Unions Instead of Nullable Flags
Most frontend and backend code eventually models asynchronous operations: data fetching, form submissions, payment processing. The common anti-pattern is a bag of independent flags: isLoading: boolean, data: T | null, error: string | null. This model permits impossible states like isLoading === true while error !== null, and forces every render path to puzzle through the combinations. A discriminated union models the state machine explicitly, with each state carrying only the data that is valid for that state.
In my experience, this is the single highest-leverage refactoring you can apply to a React codebase or an API orchestration layer. It eliminates an entire category of race condition bugs where stale error messages persist after a retry, or where data is briefly shown while a refetch is in flight without indicating staleness. The union also makes it trivial to add richer states like revalidating or polling without breaking existing consumers, because the discriminant forces consumers to decide what to do for the new state.
Structuring Remote Data With Stale-While-Revalidate Semantics
For remote data, I use four to five variants: idle, loading, success, failure, and optionally revalidating which carries both data and a loading flag. The key is that data only exists on success and revalidating, and error only exists on failure. You cannot accidentally render data when it is not there, and you cannot forget to handle the loading skeleton because the compiler requires it. This structure also composes well with pattern matching helpers and with exhaustive switches in render functions.
type RemoteData<T, E = Error> =
| { readonly status: "idle" }
| { readonly status: "loading" }
| { readonly status: "success"; readonly data: T; readonly fetchedAt: string }
| { readonly status: "failure"; readonly error: E }
| { readonly status: "revalidating"; readonly data: T; readonly fetchedAt: string };
type User = { id: string; name: string; email: string };
function renderUser(state: RemoteData<User>): string {
switch (state.status) {
case "idle":
return "No request started";
case "loading":
return "Loading...";
case "success":
return `Welcome, ${state.data.name} (fetched at ${state.fetchedAt})`;
case "failure":
return `Error: ${state.error.message}`;
case "revalidating":
return `Showing stale data for ${state.data.name} - refreshing...`;
default:
return assertNever(state);
}
}
// Transition helpers enforce valid state changes
function toLoading<T, E>(_prev: RemoteData<T, E>): RemoteData<T, E> {
return { status: "loading" };
}
function toSuccess<T, E>(data: T): RemoteData<T, E> {
return { status: "success", data, fetchedAt: new Date().toISOString() };
}
A practical tip: keep transition helpers pure and test them in isolation. I've found that housing the union definition alongside its transition functions in a single module creates a bounded context that prevents other modules from constructing invalid states directly. If you expose the union from a shared package in a monorepo, consider using TypeScript Project References for Monorepos: Build Performance and Module Boundaries to enforce that only the state machine module can create new variants.
Performance and Ergonomics Tradeoffs: Discriminated Unions Versus Class Hierarchies and Generics
Developers coming from object-oriented languages often reach for a class hierarchy with a base class and subclasses. Others try to solve the same problem with a single generic interface that has conditional properties. Both approaches can work, but they have distinct costs in TypeScript that I have learned to evaluate case by case.
Class hierarchies provide encapsulation and methods, but they introduce identity and serialization problems. An instance of a class is not structurally equal to a plain object with the same shape, instanceof checks break across realm boundaries or serialization, and you pay for prototype chains. Generic interfaces with conditional types offer flexibility, but they quickly produce unreadable error messages and fail to narrow cleanly without user-defined type guards. Discriminated unions, by contrast, are purely structural, serializable as plain JSON, and narrow with simple === checks. The trade-off is that they are data-first — you attach behavior with functions, not methods — which is idiomatic in TypeScript but requires a mindset shift if you prefer classes.
| Approach | Narrowing Mechanism | Serialization | Extensibility Cost |
|---|---|---|---|
| Discriminated Union | Discriminant property (===), automatic control-flow narrowing |
Plain JSON, no prototype loss | Add new member; compiler flags unhandled cases |
| Class Hierarchy | instanceof or custom isX() guards, brittle across bundles |
Requires manual toJSON / revivers, loses methods |
Add subclass; all instanceof checks must be audited manually |
| Generic Interface with Conditionals | User-defined type guards or type assertions | Plain JSON but types often erased | Modify conditional type; error messages become opaque |
| Enum + Separate Interfaces | Manual mapping from enum to interface, no direct narrowing | Plain JSON, but mapping must stay in sync | Update enum and every mapping table separately |
In my experience, the decision is pragmatic: use discriminated unions for domain data that crosses boundaries — API payloads, state machines, event sourcing — and reserve classes for entities that truly need private state and lifecycle methods, like a connection pool or a parser. If you need behavior per variant, write a single exhaustive function rather than distributing methods across classes. That keeps the domain logic in one auditable place. For cases where you need to abstract over discriminated unions, TypeScript Generics: Practical Examples Beyond the Basics shows how to write generic helpers like extractByKind<U, K> without losing narrowing.
When Generics Complement Rather Than Replace Unions
Generics are powerful for building reusable utilities around unions. For example, a generic match function that takes a handler map keyed by discriminant can provide a functional alternative to switch while preserving exhaustiveness if the handler map is typed as Record<Discriminant, Handler>. I have also used mapped types to derive a union of all discriminant values via U["kind"], or to build a registry of variant payloads. The key is to let the union be the source of truth and derive generics from it, not the other way around.
Validating and Evolving Discriminated Unions at API Boundaries
TypeScript types are erased at runtime, so a discriminated union guarantees safety only within the compile-time boundary. At every system edge — HTTP requests, message queues, localStorage, postMessage — you must validate that incoming JSON actually conforms to one of your variants before you treat it as a discriminated union. I have seen production incidents where an API added a new discriminant value like "kind": "applePay" and the client, which assumed the old union, silently rendered a broken state because it lacked both validation and exhaustiveness.
The robust solution is runtime validation that mirrors your static type. Libraries like Zod allow you to define a z.discriminatedUnion("kind", [...]) that parses and narrows in one step, giving you a typed value that is guaranteed to match the discriminant. This also solves the evolution problem: when you add a new variant, you add it to both the type and the schema in the same commit, and validation will reject unknown discriminants early with a useful error rather than propagating them. For full details on this bridge between static and runtime types, see Runtime Type Validation with Zod: Bridging TypeScript and External Data.
Versioning Discriminants Without Breaking Consumers
Once a discriminant is serialized and stored, changing its literal value is a breaking change. I follow two rules that have prevented painful migrations. First, never rename a discriminant value; instead, add a new variant and deprecate the old one, handling both during a transition window. Second, make the discriminant the first property and treat it as a version tag. If you need to evolve the payload shape of an existing variant, consider adding a secondary discriminator like version: 1 | 2 inside that variant rather than forking the entire union. Document the allowed values in your API contract using a standard like IETF RFC 9457 for problem details or JSON Schema, and cite that contract in code comments so future maintainers understand why the literals are frozen — see IETF RFC Standards for canonical guidance on stable interchange formats.
Finally, test the boundaries explicitly. I write unit tests that feed each valid discriminant through the parser and assert narrowing, plus one test that sends an unknown discriminant and asserts a validation error. I also write a contract test that asserts the set of discriminant literals has not changed without a deliberate version bump. Those tests are cheap and have caught accidental renames during refactors more than once.
Frequently Asked Questions
Can I use a numeric or boolean discriminant instead of a string?
Technically yes — TypeScript allows any literal type as a discriminant, including numbers and booleans. In practice I avoid them. Numeric discriminants are harder to read in logs and serialized payloads, and a boolean discriminant only supports two variants, which defeats the purpose as soon as you need a third. String literals are self-documenting, searchable, and stable across serialization formats.
How do I handle deeply nested discriminated unions?
Keep nesting shallow and compose unions rather than nesting them arbitrarily. If a variant itself has sub-variants, model the sub-variant as its own discriminated union and include it as a property. For example, a Payment with kind: "card" might have a card: CardDetails where CardDetails is itself a union of { provider: "visa" } and { provider: "amex" }. Narrow the outer discriminant first, then the inner one in a separate switch.
Does a discriminated union add runtime overhead compared to interfaces with optional fields?
No. The discriminant is just a string property, and narrowing via === is a single comparison. There is no extra object allocation or prototype chain compared to a class hierarchy, and the emitted JavaScript is identical to hand-written checks. The safety is entirely at compile time, which is why combining it with runtime validation at boundaries is essential.
What is the best way to add behavior for each variant without using classes?
Write pure functions that switch on the discriminant and handle each case exhaustively. If you prefer a functional style, create a match helper that takes an object mapping each discriminant to a handler. Both approaches keep behavior co-located and exhaustively checked, avoiding the scattering and instanceof fragility of class methods while remaining plain data that serializes cleanly.