never
Let’s imagine we want to get the area of circles and squares.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; sideLength: number };
type Shape = Circle | Square;
function getArea(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
If someone would like to add triangles…
type Triangle = { kind: "triangle"; base: number; height: number };
type Shape = Circle | Square | Triangle;
The line const _exhaustiveCheck: never = shape; will show an error, saying that it should not happen. Very useful for exhaustive checking.