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 requiresneverstops compiling when a member is left over - The
assertNever(x: never): neverhelper indefault, 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 nodefault(TS2366) as a weaker checkRecord<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
defaultthat 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.