Exhaustive switch with assertNever
Make the compiler fail when a union gains a new member that a switch does not handle.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function assertNever(value: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
default:
return assertNever(shape);
}
}How it works
Calling assertNever in the default branch means the argument must have type never. If someone adds a new variant to the union and forgets a case, the build fails at that exact line. At runtime it throws, which also catches bad data that bypassed the types.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- TypeScript Tested
Parse JSON into a typed value with a guard
Safely turn unknown JSON into a typed result by validating its shape instead of casting.
- TypeScript Tested
Typed fetch helper that checks the response
A fetch wrapper that throws on HTTP errors and validates the JSON body with a type guard.
- Python Tested
Dataclass with validation
Validate and normalize fields in __post_init__ so invalid objects can never be created.

