Course contentsShow
← TypeScript
Lesson 1408 of 1,79632. Advanced PatternsFree lesson

Union Signatures for Shared Logic

Preferring union signatures when all parameter combinations share the same implementation logic and similar return types.

Union Signatures for Shared Logic

What you'll learn: When multiple parameter combinations all execute the same implementation and return similar types, you can often replace overloads with a single union signature for simpler, more maintainable code.

The Core Idea

Function overloads excel when different parameter shapes require different logic. But sometimes you write multiple overload signatures that all feed into the same implementation — same algorithm, same return type structure. In these cases, a union signature (a single function accepting union types) is cleaner and lets TypeScript's type system do the heavy lifting.

Why Union Signatures Win for Shared Logic

With overloads, you're manually listing every valid input combination. The compiler validates calls against each overload signature separately. But when all those combinations share the same code path, you're just repeating yourself.

A union signature says: "Accept this or that, figure out which at the type level, run one implementation." You get:

  • Less code: One signature instead of multiple overload declarations
  • Easier maintenance: Add a union member once, not across multiple overloads
  • Better inference: TypeScript naturally narrows unions through your implementation

When to Prefer Unions

Choose union signatures when:

  • All parameter combinations execute the same logic
  • Return types are similar (or discriminated by input type)
  • You're validating/processing different shapes the same way

If different inputs trigger fundamentally different code paths or return incompatible types, overloads remain the better choice.

Practical Mental Model

Think of overloads as a menu with separate recipes for each item. Union signatures are a universal processor: "Give me any of these ingredients, I'll handle them all in one kitchen."

Key Takeaway: Prefer union signatures over overloads when all parameter combinations share the same implementation logic — you'll write less code and TypeScript will maintain type safety through narrowing.