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

Taught in

References