TypeScript Discriminated Unions: Stop Writing Unsafe Optional Flags
Stop littering your code with optional flags that allow impossible states, and learn how discriminated unions force TypeScript to make impossible bugs illegal.
You will learn why bloated interfaces with optional fields lead to production outages, how TypeScript uses literal types to discriminate states, and how to rewrite messy components into bulletproof state machines.
1. The big idea: Why your state objects are a ticking time bomb
Picture this: It is 2:14 AM on a Sunday. PagerDuty is screaming because the checkout page is throwing a TypeError: Cannot read properties of undefined (reading 'cardNumber'). You open up the codebase, look at the API response interface, and see this absolute crime scene of software engineering:
interface CheckoutState {
data?: OrderDetails;
error?: string;
isLoading: boolean;
isSuccess: boolean;
}Look closely at that interface. Nothing stops a junior developer (or you, three weeks ago after four energy drinks) from writing code where isLoading is true, error is "Network timeout", and data contains valid order details. That is not a state; that is a Schrödinger's cat box of corrupted data. Your application is simultaneously loading, failing, and succeeding.
TypeScript is supposed to protect us from these disasters. Yet, when we use optional flags (?) for everything, we hand the compiler a blindfold and ask it to drive our production environment down a winding mountain road.
A discriminated union (sometimes called a tagged union or algebraic data type) solves this by forcing mutually exclusive states. Instead of one big object where everything is optional, you define separate shapes for every possible reality of your app, tied together by a common literal field (the "discriminant"). If an error happens, data literally cannot exist. The type system enforces physics.
2. Diagnosing the optional-flag anti-pattern
Let us look at how this anti-pattern infects your components. Here is a typical React component fetching user profile data using our broken CheckoutState-style approach:
interface ProfileState {
user?: User;
error?: Error;
loading: boolean;
}
function ProfileCard({ state }: { state: ProfileState }) {
// Woe to any developer who forgets this check
if (state.loading) {
return <div>Loading your digital life...</div>;
}
// Wait, what if there is an error AND a stale user object?
if (state.error) {
return <div>Error: {state.error.message}</div>;
}
// TypeScript still thinks state.user might be undefined here
// unless you add another exclamation mark or optional chaining.
return (
<div>
<h1>{state.user!.name}</h1>
<p>{state.user!.email}</p>
</div>
);
}Notice that exclamation mark !. That is the non-null assertion operator, which is essentially a developer whispering to TypeScript: "Trust me, I know what I am doing, and if I am wrong, let the runtime burn." It is a confession of failure.
When your types do not match reality, you spend half your time writing defensive checks (if, ??, ?., !) against states that should never even be allowed to compile.
3. Fixing it with Discriminated Unions
To fix this, we break down our single messy interface into distinct, isolated states. Each state shares a single property—usually called status or tag—with a unique string literal value.
Let us refactor our profile state into a clean discriminated union:
type ProfileState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; user: User }
| { status: 'error'; error: Error };Look at that definition. When status is 'success', the user property is required, and there is no room for an error or a loading flag. When status is 'error', an Error object is guaranteed to exist.
Now, watch how clean our component becomes when we use a switch statement to let TypeScript narrow the type automatically:
function ProfileCard({ state }: { state: ProfileState }) {
switch (state.status) {
case 'idle':
return null;
case 'loading':
return <div>Loading your digital life...</div>;
case 'error':
// TypeScript knows state.error exists here!
return <div>Error: {state.error.message}</div>;
case 'success':
// TypeScript knows state.user exists here! No exclamation marks!
return (
<div>
<h1>{state.user.name}</h1>
<p>{state.user.email}</p>
</div>
);
}
}Discriminated Union Narrowing FlowClick to expandClick to collapse
Inspect the literal value of the status property
The compiler restricts the object shape to the matching union member
Access properties safely without optional chaining or assertions
4. Verification and exhaustive checking
What happens when your product manager comes back next week and says, "We need a refreshing state while the user updates their profile in the background"?
If you use optional flags, you might forget to handle it in three different UI components, leading to silent UI glitches. With discriminated unions, TypeScript can enforce exhaustiveness checking.
We use a never-check helper function to ensure that every possible branch of the union is handled:
function assertNever(x: never): never {
throw new Error(`Unexpected object: ${JSON.stringify(x)}`);
}
function ProfileCard({ state }: { state: ProfileState }) {
switch (state.status) {
case 'idle':
return null;
case 'loading':
return <div>Loading...</div>;
case 'error':
return <div>{state.error.message}</div>;
case 'success':
return <div>{state.user.name}</div>;
default:
// If you add a new status and forget a case, TypeScript will fail to compile here!
return assertNever(state);
}
}If you add a new union member and forget to update your switch statement, TypeScript will throw a compile-time error right inside your editor. The compiler becomes your automated QA engineer.
Run npx tsc --noEmit in your project terminal after refactoring. If your build passes without a single ! non-null assertion, congratulations—you have successfully eliminated an entire class of runtime bugs.
Common pitfalls
| Mistake | Why it hurts | Fix |
|---|---|---|
Using generic boolean flags (isLoading, isError) | Allows impossible state combinations like loading true with an error present | Use a single status literal field ('loading', 'error') |
Forgetting the default exhaustiveness check | Adding new states later leads to silent UI failures instead of compile errors | Pass the default branch to an assertNever helper function |
| Sharing optional fields across union branches | Reintroduces ambiguity and forces you to write unnecessary runtime checks | Keep union branch shapes completely distinct and mutually exclusive |
What you learned
- Optional flags (
?) allow impossible states that corrupt your application data and cause production crashes. - Discriminated unions use a literal tag field (like
status) to model mutually exclusive states cleanly. - TypeScript automatically narrows object shapes inside
switchorifblocks based on the discriminator. - Exhaustiveness checking with
assertNeverguarantees that future state additions will never be accidentally ignored by your UI components.