Discriminated UnionsAdvanced
1Question 1 of 1
typescriptWhat are Discriminated Unions and how do they enable exhaustive pattern matching?
Explanation & Concept
A Discriminated Union (or Tagged Union) is a pattern where multiple object types share a common literal discriminator property (e.g. `type`, `kind`, `status`).
TypeScript uses this discriminator to narrow the exact type in `switch` statements and enforce exhaustive checking via the `never` type.
Code Example
typescript
type NetworkState =
| { state: "loading" }
| { state: "success"; response: string }
| { state: "failed"; code: number };
function renderNetwork(status: NetworkState) {
switch (status.state) {
case "loading":
return "Loading spinner...";
case "success":
return `Data: ${status.response}`;
case "failed":
return `Error code: ${status.code}`;
default:
// Exhaustiveness check: fails compilation if any state is unhandled
const _exhaustiveCheck: never = status;
return _exhaustiveCheck;
}
}How It Works & Key Takeaways
If a developer adds a new state (like `{ state: 'idle' }`), TypeScript immediately produces a compile-time error at the `default` branch until it is handled.
Mock Test · 1 Questions · Optional
Ready for Function Overloads?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions