typescript / expert
Snippet
Exhaustiveness Checking with the 'never' Type
By assigning a variable to the 'never' type in a default branch, you create a compile-time check for exhaustiveness. If a new member is added to the 'Shape' union, the code will fail to compile until the new case is handled.
snippet.ts
1
2
3
4
5
6
7
8
9
10
11
type Shape = { type: "circle" } | { type: "square" };function getArea(shape: Shape) {switch (shape.type) {case "circle": return Math.PI;case "square": return 1;default:const _exhaustiveCheck: never = shape;return _exhaustiveCheck;}}
Breakdown
1
const _exhaustiveCheck: never = shape
Forces the compiler to verify that 'shape' has no remaining possible types at this point.
2
default:
The safety net that catches unhandled union members during development.