Skip to content
Preptima
mediumCodingConceptMidSeniorStaff

How do you make the compiler fail when somebody adds a new variant to a union you switch on?

A TypeScript exhaustive switch uses a discriminated union and a never check so the compiler fails when a new variant is added but not handled. This turns future union growth into a compile-time error. It also connects discriminated unions to the point an interviewer is testing.

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Model the cases as a discriminated union and finish the switch with a never assignment or assertNever helper. When another case is added, the default branch no longer type-checks until the new case is handled.

Was this answer helpful?

Likely follow-ups

  • The variants come from a string enum rather than literal types. What changes about any of this?
  • A colleague rewrites the switch as an if-else chain and the check stops working. Why?
  • How do you get a comparable guarantee for a discriminant that arrived from an API and might be a variant you have never heard of?
  • Would you rather the failure appeared where the handler table is defined or at the call site, and why?

Related questions

Further reading