TypeScript discriminated unions
- Version
- es2025
- Since
- 2.0
- Review
- Draft
Summary#
A discriminated union gives each member a shared property with a distinct literal type. Testing that property narrows the value to the matching member.
Syntax#
type Result = { status: "ok"; value: string }
| { status: "error"; message: string };
Example#
type Delivery = { mode: "pickup"; locker: string }
| { mode: "courier"; windowHours: number };
function label(delivery: Delivery): string {
switch (delivery.mode) {
case "pickup":
return `Locker ${delivery.locker}`;
case "courier":
return `Delivery within ${delivery.windowHours} hours`;
default: {
const unhandled: never = delivery;
throw new Error(`Unknown delivery mode: ${unhandled}`);
}
}
}
console.log(label({ mode: "pickup", locker: "B7" }));
console.log(label({ mode: "courier", windowHours: 2 }));
Expected output#
Locker B7
Delivery within 2 hours
Common mistakes#
A discriminant typed as plain string cannot select a member. An object stored in a variable first may have its mode widened to string, so annotate it with the union type. The never assignment reports missing cases at compile time. Validate untrusted input before passing it to the function.
Version applicability#
TypeScript 2.0 added narrowing for tagged unions and the never type used by the exhaustiveness check.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0