Skip to the solution
MediumFrontend9 min read

How do you do exhaustiveness checking?

885 views

The problem

Question presented to candidate: "A teammate adds a new status to a union type, and three switch statements across the codebase silently stop handling it. How would you make the compiler catch that the next time?"

What a strong answer should cover:

  • Exhaustiveness checking: once every member of a union is handled, the narrowed type in the remaining branch is never, and code that requires never stops compiling when a member is left over
  • The assertNever(x: never): never helper in default, which also throws at run time for data that escaped the type system
  • x satisfies never (4.9+) as a helper-free compile-time check, and a declared return type with no default (TS2366) as a weaker check
  • Record<Union, T> lookup tables, which force every key to be present
  • The error messages name the forgotten member, which makes the fix obvious; the check works on literal unions and discriminated unions alike
  • Trade-offs: run-time safety for external data, and why a default that returns a fallback value defeats the check

Code / implementation expected: Yes β€” a switch over a union with an assertNever default, and the error you get after adding a member.

  • never
  • exhaustive

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptassertNever and satisfies never on a string union
TypeScriptObject unions, Record lookup tables and the return-type check

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 26 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are mapped types?

Continue