Discriminated Unions for State
What you'll learn: How to use discriminated unions to model application state so that invalid combinations like "loading with data" become impossible to represent.
The Core Idea
When modeling state (like data fetching), beginners often create types where multiple flags can be true simultaneously:
type LoadingState = {
isLoading: boolean;
error: string | null;
data: string | null;
};
This design has a fatal flaw: it allows impossible states. Your state could be { isLoading: true, error: "Failed", data: "Result" } all at once. What does that even mean?
Discriminated unions solve this by making states mutually exclusive. Each state is a separate type with a unique tag (the discriminant), and TypeScript ensures only one can exist at a time.
The Solution Pattern
type FetchState =
| { status: 'loading' }
| { status: 'error'; message: string }
| { status: 'success'; data: string };
Now your state can only be in one situation:
- Loading (no error, no data possible)
- Error (includes message, no data)
- Success (includes data, no error)
The status property acts as the discriminant—TypeScript uses it to narrow which variant you're dealing with:
function renderUI(state: FetchState) {
switch (state.status) {
case 'loading':
return "Loading...";
case 'error':
return `Error: ${state.message}`; // TypeScript knows message exists
case 'success':
return `Data: ${state.data}`; // TypeScript knows data exists
}
}
Notice how inside each case, TypeScript automatically knows which properties are available. Try accessing state.data in the 'loading' branch—TypeScript will reject it.
Why This Matters
This pattern is type-driven design at its best. You're using the type system to enforce business rules: "loading means we don't have data yet" isn't just a comment—it's enforced by the compiler.
Key Takeaway: Discriminated unions turn state management from a source of bugs into a compile-time guarantee. Invalid states become unrepresentable, and TypeScript guides you to handle every valid case correctly.