Advertisement
Advanced TypeScript, Discriminated Unions & Exhaustiveness Checking

How does exhaustiveness checking behave differently if the union member types overlap structurally instead of being cleanly discriminated?

Short answer

If variants don't share a unique literal discriminant (or their shapes overlap ambiguously), narrowing based on property checks becomes unreliable — TypeScript may not be able to distinguish which variant you're in, weakening or breaking exhaustiveness checking entirely, since…

Save TypeScript mock interview
Advertisement
AModel answer
If variants don't share a unique literal discriminant (or their shapes overlap ambiguously), narrowing based on property checks becomes unreliable — TypeScript may not be able to distinguish which variant you're in, weakening or breaking exhaustiveness checking entirely, since the 'never' trick relies on the compiler correctly eliminating all known variants.
// Poorly discriminated - both have 'value: number', ambiguous
type A = { type: 'a'; value: number };
type B = { value: number }; // no matching 'type' discriminant at all
type Bad = A | B; // narrowing on 'type' alone won't safely narrow B
Real-world example
Debugging why a switch/case exhaustiveness check silently fails to catch a missing case, tracing it to a poorly-discriminated union.
Likely follow-ups
  • What's the fix when you discover a union isn't properly discriminated like this?
Related topics