TypeScript
Beginner
1 min read
Exhaustiveness Checking with Enums
Example
// Exhaustiveness helper
function assertNever(value: never, message = "Unhandled case"): never {
throw new Error(`${message}: ${JSON.stringify(value)}`);
}
enum TrafficLight { Red = "RED", Yellow = "YELLOW", Green = "GREEN" }
function getAction(light: TrafficLight): string {
switch (light) {
case TrafficLight.Red: return "Stop";
case TrafficLight.Yellow: return "Caution";
case TrafficLight.Green: return "Go";
default:
// If a new member is added without updating this switch,
// TypeScript will error here because light is no longer never
return assertNever(light);
}
}
// Discriminated union exhaustiveness
type PaymentMethod =
| { type: "card"; last4: string; brand: string }
| { type: "paypal"; email: string }
| { type: "crypto"; address: string; coin: string };
function describePayment(method: PaymentMethod): string {
switch (method.type) {
case "card":
return `${method.brand} card ending in ${method.last4}`;
case "paypal":
return `PayPal account ${method.email}`;
case "crypto":
return `${method.coin} wallet ${method.address}`;
default:
return assertNever(method);
}
}
console.log(describePayment({ type: "card", last4: "4242", brand: "Visa" }));
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript