Course contentsShow
← TypeScript
Lesson 1670 of 1,79638. Common Patterns and AntipatternsFree lesson

The Readability Trade-off

Unions are more explicit and readable; generics are more flexible but can obscure intent if overused.

The Readability Trade-off

You'll learn how unions and generics each sacrifice different things: unions trade flexibility for explicitness, while generics trade immediate clarity for power.

The Core Trade-off

Both unions and generics solve the problem of handling multiple types, but they make opposite compromises:

Unions are immediately readable but inflexible. When you see string | number | boolean, you know exactly what's allowed—nothing more, nothing less. The type system enforces that closed set. However, you can't dynamically preserve which specific type was passed through a function.

Generics are flexible and precise but require mental overhead. A type parameter like <T> says "some type I don't know yet," which preserves exact type information through transformations. But readers must trace T through the entire function to understand what's happening. The intent becomes obscured by abstraction.

When Each Wins

Use unions when:

  • You have a known, fixed set of possibilities
  • Readers need to immediately grasp what's valid
  • You're defining configuration options or state variants
  • The API is consumed more than implemented

Use generics when:

  • You need type preservation (what goes in comes out)
  • The function is truly polymorphic across many types
  • You're building reusable utilities
  • The pattern is already familiar (like Array<T>)

The Overuse Problem

Generic overuse makes code cryptic. Seeing <T, U, K extends keyof T> forces readers to become type detectives. If you could have written { id: string; name: string } directly, that's often better.

Union overuse creates brittleness. A union of 15 string literals might be "explicit," but it becomes a maintenance nightmare and obscures the underlying domain concept that those strings represent.

Balancing Both

The best code often combines them strategically: use unions for method parameters where callers need clarity, but use generics internally where type preservation matters. Consider your reader's journey through the code, not just type correctness.

Key Takeaway: Unions favor readers who need to understand constraints at a glance; generics favor flexibility but require readers to trace type flow—choose based on who's reading and what they need to accomplish.