Discriminated Unions for Safe Pattern Matching
Add a common literal field to union members for type safety.
Discriminated Unions for Safe Pattern Matching is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Welcome
The Discriminant Property
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;Narrowing with if Checks
function area(shape: Shape): number {
if (shape.kind === 'circle') {
return Math.PI * shape.radius ** 2;
}
return shape.side ** 2; // narrowed to Square
}Narrowing with switch/case
function describe(shape: Shape): string {
switch (shape.kind) {
case 'circle': return `Circle r=${shape.radius}`;
case 'square': return `Square s=${shape.side}`;
}
}Exhaustiveness with never
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'square': return shape.side ** 2;
default:
const _exhaustive: never = shape;
throw new Error('Unhandled shape');
}
}Result Type Pattern
type Ok<T> = { ok: true; value: T };
type Err = { ok: false; error: string };
type Result<T> = Ok<T> | Err;Action Type Pattern (Redux-style)
type Action =
| { type: 'INCREMENT'; amount: number }
| { type: 'DECREMENT'; amount: number }
| { type: 'RESET' };Multiple Discriminant Properties
type AdminUser = { role: 'admin'; permissions: string[] };
type RegularUser = { role: 'user'; credits: number };
type User = AdminUser | RegularUser;Non-Discriminated Unions Still Narrow
type StringOrArr = string | string[];
function flatten(val: StringOrArr): string[] {
return Array.isArray(val) ? val : [val];
}Discriminated Unions vs Class Hierarchies
Real-World: HTTP Response Union
type ApiState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };Quick Check
Recap
Frequently asked questions
Is the “Discriminated Unions for Safe Pattern Matching” lesson free?
Yes — the full text of “Discriminated Unions for Safe Pattern Matching” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Discriminated Unions for Safe Pattern Matching”?
Add a common literal field to union members for type safety. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Discriminated Unions for Safe Pattern Matching” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Union Types: A or B
- Intersection Types: A and B
- Discriminated Unions for Safe Pattern Matching
- Practical Patterns with Union and Intersection