Hone

Lessons · TypeScript · never: proving you covered every case

Every case, or a compile error

In a switch over a discriminated union, assigning the default case to a never variable makes adding a new variant a compile error until it is handled.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Add a third shape and every switch that forgot it fails to compile, instead of silently returning the wrong thing at runtime. The compiler becomes the checklist.

How to think about it

Handle each variant in its own case. In default, assign the value to a variable typed never. If every case is handled, that assignment compiles; a new variant breaks it exactly where it matters.

Worked example

type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
Two variants.
function shapeArea(s: Shape): number {
Takes either.
  switch (s.kind) {
The tag decides.
    case "circle": return 3.14 * s.r * s.r;
Circle.
    case "square": return s.s * s.s;
Square.
    default: { const check: never = s; return check; }
Every case is handled, so s is never here. Add a variant and this line fails to compile.
  }
}

Your turn

The exhaustiveness check.

default: { const check:  = s; return check; }

The trap

Without the never check, adding a variant compiles, and the new shape falls through to a wrong result at runtime.

Practise never: proving you covered every case on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.