The TypeScript pattern I use every week: discriminated unions
If I had to keep only one TypeScript pattern, it would be the discriminated union. I use it almost every week, usually to answer one question: what state is this thing in, and what data exists in that state?
People often sell it as a bug catcher. For me it’s mostly about something less dramatic: keeping code organized, easy to read, and safe to refactor.
The problem: state you have to guess
Here’s the shape I see in a lot of components that fetch data:
type QuoteState = {
loading: boolean;
error?: string;
data?: Quote;
};
It looks reasonable, but it allows states that make no sense: loading: true with an error, or loading: false with no data and no error. Every component that reads it has to guess which combination it got, and every reader of the code has to guess too.
The fix: one field that says which state you’re in
type QuoteState =
| { status: 'loading' }
| { status: 'error'; message: string }
| { status: 'success'; data: Quote };
Now there are exactly three states, and each one carries only the data that exists in it. The status field is the discriminant: once you check it, TypeScript narrows the type for you.
function QuoteCard({ state }: { state: QuoteState }) {
switch (state.status) {
case 'loading':
return <Skeleton />;
case 'error':
return <ErrorMessage text={state.message} />;
case 'success':
return <Price value={state.data.price} />;
}
}
Inside the 'success' branch, state.data is guaranteed to be there. In the 'loading' branch, reading state.data is a compile error. The type reads like documentation: anyone opening the file sees every state at a glance.
Refactors with a to-do list
The part I like most is exhaustiveness checking. Add a default that assigns to never:
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}
// ...
default:
return assertNever(state);
Later, someone adds { status: 'stale'; data: Quote } for data that’s shown while a refresh is in flight. Every switch that doesn’t handle 'stale' now fails to compile, so the compiler hands you the list of places to update. That’s what makes refactors feel safe.
Types stop at the network boundary
There’s a catch: TypeScript only knows about the values you told it about. The data itself comes from a service, and nothing stops that service from sending a status your union has never heard of.
That’s how I use discriminated unions day to day: as the agreement between the front end and the data schemas we’ve committed to. If the backend and the UI agree on a set of shapes, the union is that agreement in code, and keeping it aligned means no surprises in production.
When something outside the agreement does arrive, I don’t want the page to crash, and I don’t want it to fail silently either. So the boundary checks the discriminant, falls back gracefully, and logs what it saw:
const KNOWN_STATUSES = ['loading', 'error', 'success'] as const;
function parseQuoteState(raw: unknown): QuoteState {
const status = (raw as { status?: unknown })?.status;
if (KNOWN_STATUSES.includes(status as QuoteState['status'])) {
return raw as QuoteState; // validate the rest with your schema library of choice
}
logger.warn('quote.unknown_status', { status });
return { status: 'error', message: 'Something went wrong' };
}
The log line is the important part. A monitor watches how often it fires: one stray value is noise, but if it keeps happening, it raises a low-severity (sev3) alert so a developer can follow up. Usually it means a schema changed on one side and not the other, and the alert tells us before users notice. Libraries like Zod can generate this kind of check straight from a discriminated union, so the type and the validation can’t drift apart.
Where I use it
- Async UI state: loading, error, success, empty.
- Content that comes in several shapes: a card that can be a game score, a stock quote, or a forecast, each with its own fields. It’s the same idea behind the schema-driven cells in one table component for three products.
- Events and actions: reducers, analytics events, messages between components.
The rule of thumb
If you catch yourself writing several optional fields plus a comment explaining which ones go together, that comment is a union type waiting to happen. Give each state a name, let the compiler keep track of them inside your code, and let your logs and monitors keep track of them at the edges.