Lesson 3 of 8
Discriminated Unions - Type-Safe State Machines
A discriminated union is a union of object types where each member has a common 'discriminant' property with a unique literal type. TypeScript uses this discriminant to narrow automatically and exhaustively. Discriminated unions are the primary pattern for modeling state, actions, API responses, and finite states in production TypeScript.
Discriminated Unions - State Machine Pattern
// ── Discriminated union - each member has a unique "kind" field ─
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
case "triangle":
return 0.5 * shape.base * shape.height;
default:
// Exhaustiveness check - if a new shape is added to Shape
// and not handled, TypeScript errors here:
const _exhausted: never = shape;
throw new Error(`Unknown shape: ${JSON.stringify(_exhausted)}`);
}
}
// ── Network request state machine ─────────────────────────────
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string; retryCount: number };
function renderTask(state: RequestState<Task>): string {
switch (state.status) {
case "idle": return "Ready";
case "loading": return "Loading...";
case "success": return `Task: ${state.data.title}`;
case "error": return `Error: ${state.error} (retry ${state.retryCount})`;
}
}
// ── Discriminated union without switch - if/else narrowing ─────
function getErrorMessage(state: RequestState<unknown>): string | null {
if (state.status === "error") {
return state.error; // ✅ narrowed - state.error exists
}
return null;
}
// ── Task Manager - typed task action ─────────────────────────
type TaskAction =
| { type: "CREATE"; payload: { title: string; priority: Priority } }
| { type: "UPDATE"; payload: { id: number; changes: Partial<Task> } }
| { type: "DELETE"; payload: { id: number } }
| { type: "ARCHIVE"; payload: { id: number; reason: string } };
function applyTaskAction(tasks: Task[], action: TaskAction): Task[] {
switch (action.type) {
case "CREATE": return [...tasks, createTask(action.payload)];
case "DELETE": return tasks.filter(t => t.id !== action.payload.id);
case "ARCHIVE": return tasks.map(t =>
t.id === action.payload.id ? { ...t, status: "archived" as const } : t
);
default:
const _: never = action;
throw new Error("Unknown action");
}
}Common Mistakes
- Using a generic `type` field without making it a literal - `type: string` doesn't discriminate. Use specific literals: `type: 'CREATE'`.
- Forgetting the exhaustiveness `never` check - without it, adding a new union member is silently unhandled. Always add the `never` default branch in production switch statements.
- Mutating state in action handlers - discriminated unions work best with immutable updates. Always return new array/object references rather than mutating existing ones.
Tip
Tip
Practice Discriminated Unions TypeSafe State Machines in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Discriminated Unions - Type-Safe State Machines
Practice Task
Note
Practice Task - (1) Write a working example of Discriminated Unions TypeSafe State Machines from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Discriminated Unions TypeSafe State Machines is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- A discriminated union is a union of object types where each member has a common 'discriminant' property with a unique literal type.
- Using a generic `type` field without making it a literal - `type: string` doesn't discriminate. Use specific literals: `type: 'CREATE'`.
- Forgetting the exhaustiveness `never` check - without it, adding a new union member is silently unhandled. Always add the `never` default branch in production switch statements.
- Mutating state in action handlers - discriminated unions work best with immutable updates. Always return new array/object references rather than mutating existing ones.
Finished this lesson?