typescript / expert
Snippet
Exhaustive Union Discriminant Assertion via Never Type Check
This snippet ensures compile-time exhaustiveness checking for discriminated unions using the `never` type. If a developer adds a new variant to the union without updating control flow handlers, TypeScript triggers a build error because the unhandled type cannot be assigned to `never`.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class UnreachableCaseError extends Error {constructor(val: never) {super(`Unreachable case encountered: ${JSON.stringify(val)}`);}}type Shape = { kind: "circle"; radius: number } | { kind: "square"; size: number };function getArea(shape: Shape): number {switch (shape.kind) {case "circle": return Math.PI * shape.radius ** 2;case "square": return shape.size ** 2;default: throw new UnreachableCaseError(shape);}}
Breakdown
1
class UnreachableCaseError extends Error {
Custom error class extending standard Error for runtime fallback validation.
2
constructor(val: never) {
Restricts parameter type strictly to never, ensuring static exhaustiveness.
3
function getArea(shape: Shape): number {
Calculates area based on the discriminated union property 'kind'.
4
default: throw new UnreachableCaseError(shape);
Fails compilation if any discriminated union variant remains unhandled.