assertNever Utility
April 15, 2025
export function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
This tiny function is super helpful when working with discriminated unions in TypeScript. It ensures that every possible case is handled — and if a new case is added but not accounted for, you'll get a compiler error (or a runtime exception in development).
Example Usage
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; sideLength: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
return assertNever(shape);
}
}
This pattern helps catch bugs early when you forget to handle a new kind. TypeScript will complain if shape is not of type never in the default case — meaning you've missed a case in the switch.
Tip: You’ll appreciate this the next time you refactor a union type!