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

When to Use Overloads

Recognizing scenarios where overloads provide clearer types than a single union signature for varied input-output relationships.

When to Use Overloads

You'll learn: How to recognize when function overloads provide clearer, more precise types than a single signature with union parameters.

The Decision Point

You've learned how to write function overloads, but the key question is: when should you? Function overloads shine when different input types produce different output types in predictable ways that a single union signature can't capture accurately.

The Union Problem

Consider a function that accepts either a string or number and returns a corresponding type:

// Single signature with unions - loses type precision
function format(value: string | number): string | number {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

const result1 = format("hello");  // Type: string | number (too broad!)
const result2 = format(42);       // Type: string | number (also too broad!)

The problem? TypeScript knows you'll get string | number back, but not which one based on your input.

When Overloads Win

Overloads let you express the input-output relationship precisely:

// Overloads - precise type relationships
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

const result1 = format("hello");  // Type: string (precise!)
const result2 = format(42);       // Type: string (precise!)

Now TypeScript understands the exact return type based on your input.

Use Overloads When...

  1. Input type determines output type (like generic-style behavior without generics)
  2. Different parameter combinations produce different returns
  3. Optional parameters change the return type
  4. You need to model multiple distinct call patterns

Don't Use Overloads When...

  • A single signature with unions already gives precise types
  • Generics would express the relationship more clearly
  • You're just handling different primitive inputs that return the same type

Key Takeaway: Use overloads when the relationship between input and output types matters for type safety, and unions would lose that precision. Overloads are documentation that different input patterns yield meaningfully different outputs.