QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
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

typescript
typescript
1
2
3
4
5
6
7
8
9
10
11
12
type 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 Code

Industry 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.