Advanced 18 min readModule: Module 7: Type Narrowing & Discriminated Unions
Discriminated Unions & Custom Type Predicates
Eliminate impossible UI states using discriminated union tagged objects and custom 'x is Type' predicates.
What You Will Learn in This Lesson
- Discriminated Unions with common literal tag properties
- Writing custom user-defined type guards (is fish)
- Exhaustiveness checking with the 'never' type
Introduction & Core Concept
Type narrowing is the process by which TypeScript refines a broad type (like string | number) into a specific type based on conditional checks.
WHY DOES THIS MATTER IN THE REAL WORLD?
Discriminated unions make invalid application states mathematically impossible to represent.
Discriminated Union State Handler
typescripttypescript
123456789101112type AsyncState<T> =| { status: "loading" }| { status: "success"; data: T }| { status: "error"; error: string };function renderUI(state: AsyncState<string[]>) {if (state.status === "success") {console.log("Loaded items:", state.data.length);}}renderUI({ status: "success", data: ["HTML", "CSS"] });
Line-by-Line Technical Breakdown
1Exhaustive checks with 'never' ensure you handle every union branch in switch statements.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[TYPESCRIPT]
TYPESCRIPT SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Always tag state representations with a common 'status' or 'kind' property.
Lesson Summary & Core Takeaways
- Discriminated unions provide bulletproof state machine modeling in TypeScript.