Use Specific Types Instead of Unions When Possible
You'll learn how narrowing your type definitions can dramatically improve TypeScript's compilation performance by reducing the search space during type checking.
Understanding the Problem
When TypeScript checks types, it needs to verify that your code satisfies all type constraints. With union types, the compiler must consider every possible member of the union for every operation. The larger and more complex your unions, the more work TypeScript does.
Think of it like searching for a book in a library. If you say "find me a book that's either fiction, non-fiction, biography, mystery, romance, sci-fi, or history," the librarian has to check seven different categories. But if you say "find me a mystery novel," they only search one section.
How Specific Types Reduce Checking Overhead
Broad union types force the compiler to:
- Distribute type operations across all union members
- Check assignability against multiple alternatives
- Resolve conditional types for each branch
- Maintain larger internal type representations
Specific types give TypeScript a direct path to verification instead of exploring multiple branches.
When to Replace Unions
Replace unions with specific types when:
- You're using a union "just in case" but only one variant actually flows through in practice
- A union represents distinct contexts that could be modeled as separate functions or overloads
- Generic type parameters can capture the specific type instead of listing possibilities
- The union grows beyond 5-7 members and becomes a performance bottleneck
The Practical Impact
Imagine a utility function that accepts string | number | boolean | null | undefined | symbol | bigint. Every call site forces TypeScript to check all seven possibilities. If 99% of your uses are actually string, you're paying the performance cost unnecessarily.
Better: Create focused functions with specific types, or use a generic constrained to the types you actually need.
Key Takeaway: Broad union types make TypeScript work harder. When you know the specific type that flows through your code, use it directly—your compiler will thank you with faster type checking and clearer error messages.