Implementation: (maybe Function.unreachable)
function unreachable(_val) {
throw new TypeError()
}
Usage:
function route(direction) {
switch (direction) {
case "up": case "down": return "left";
case "left": case "right": return "up";
default: Function.unreachable(direction)
}
}
The real power of this helper is used with TypeScript. This function should have type signature (val: never) => never
type Direction = 'up' | 'down' | 'left' | 'right'
function route(direction: Direction) {
switch (direction) {
case "up": case "down": return "left";
case "left": case "right": return "up";
default: Function.unreachable(direction)
}
}
It will provide an exhaustive matching guard, which means if I'm missing some cases, it will become a compile error.
Let's say I add one new direction to the type Direction
type Direction = 'up' | 'down' | 'left' | 'right' | 'stay'

The compiler will tell me that: hey! direction is no longer type never (when you exhaustive all possibilities of a variable), you still have one case to check!
This unreachable function is very useful and I have implemented it in many of my repos.
Implementation: (maybe
Function.unreachable)Usage:
The real power of this helper is used with TypeScript. This function should have type signature
(val: never) => neverIt will provide an exhaustive matching guard, which means if I'm missing some cases, it will become a compile error.
Let's say I add one new direction to the type
DirectionThe compiler will tell me that: hey!
directionis no longer typenever(when you exhaustive all possibilities of a variable), you still have one case to check!This
unreachablefunction is very useful and I have implemented it in many of my repos.