assertNever
A small helper function taking a parameter of type never, called in the default branch of a switch to prove every case was handled.
In more detail
If every union member has a case, the value reaching default is never and the call compiles. When someone adds a new member, the value is no longer never and the compiler points at the switch. At run time the helper throws, which also catches unexpected values from outside.
Example
function assertNever(x: never): never { throw new Error(`Unhandled: ${JSON.stringify(x)}`); }Related terms
- never (type) — The TypeScript type with no values, used for code that can never be reached or functions that never return.
- exhaustiveness checking — Having the compiler prove that code handles every possible member of a union, so a newly added member causes a compile error.
- switch statement — A statement that compares one value against a list of cases and runs the matching branch, with a default for everything else.
- discriminated union — A type made of several object shapes that share one literal field, such as status or type, whose value tells them apart.
Taught in
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Discriminated Unions: Tagged Variants And Pattern Matching — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript