Check exhaustiveness with never
Assign the leftover value to a never variable in the default branch, and the compiler fails the build when you add a union member and forget a case.
A switch over a union compiles even when you forget a case. Assigning the value to never in the default branch makes the forgetting a compile error.
type Shape =
| { kind: 'circle'; r: number }
| { kind: 'square'; side: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.r ** 2;
case 'square':
return shape.side ** 2;
default: {
const unreachable: never = shape;
throw new Error(`unhandled shape ${JSON.stringify(unreachable)}`);
}
}
}shapes.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.After the two case branches, TypeScript narrows shape to what is left, which is the triangle. A triangle cannot be assigned to never, so the line fails and the message names the case you missed. Add case 'triangle' and the leftover type becomes never, so the error disappears. See exhaustiveness checking.
Keep the throw. At runtime, data that skipped your types, such as a payload from a newer server, can still reach the default branch, and throwing is better than returning undefined.