Course contentsShow
← TypeScript
Lesson 416 of 1,7969. Union TypesFree lesson

Adding Variants Without Breaking Code

How exhaustiveness checks catch missing cases when new variants are added to the union.

Adding Variants Without Breaking Code

What you'll learn: How exhaustiveness checks automatically catch missing cases when you add new variants to a discriminated union, preventing bugs before runtime.

The Problem of Growing Unions

Imagine you've built a well-typed discriminated union handling three payment methods, with exhaustiveness checking ensuring all cases are handled. Your code is working perfectly in production.

Then business requirements change—you need to add a fourth payment method. In regular JavaScript, you'd add the new case and hope you remembered to update every switch or if/else chain throughout your codebase. Miss one spot, and you have a runtime bug.

TypeScript's Safety Net

With discriminated unions and never-based exhaustiveness checking, TypeScript becomes your safety net. When you add a new variant to the union type, every switch or if/else that claimed to be exhaustive will immediately fail type-checking.

The default: const _exhaustive: never = value pattern you learned earlier isn't just for catching current mistakes—it's for catching future mistakes:

  • You add CryptoPayment to your PaymentMethod union
  • TypeScript re-evaluates all your exhaustiveness checks
  • Any function that doesn't handle CryptoPayment now has a type error
  • The compiler tells you exactly where you need to add code

The Compiler Guides Your Updates

Instead of hunting through your codebase wondering "did I update all the payment handlers?", TypeScript generates a to-do list for you. Each type error marks a spot that needs the new variant handled.

Key Takeaway: Exhaustiveness checking transforms adding union variants from a dangerous refactoring into a guided, compile-time-safe process where the type system tells you exactly what needs updating.