Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// 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" }));
Result
Open