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

Unions vs Overloads

When to use union types versus function overloads for accepting multiple input types.

Unions vs Overloads

You'll learn when to choose union types versus function overloads for accepting multiple input types.

Both union types and function overloads allow a function to accept different types of input, but they serve different purposes and communicate different intentions to TypeScript.

The Core Difference

Union types say "this parameter can be Type A or Type B, and I'll handle both possibilities the same way initially." You then narrow inside the function to handle each case.

Function overloads say "this function behaves differently depending on what you pass in, and the return type or behavior changes accordingly." They describe multiple distinct call signatures.

When to Use Union Types

Use unions when the function logic handles different input types but the relationship between input and output types is straightforward:

function formatValue(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

formatValue("hello"); // string
formatValue(42);      // string

The return type is always string regardless of input type.

When to Use Overloads

Use overloads when the return type or behavior fundamentally changes based on the input type:

function processInput(input: string): string[];
function processInput(input: number): number;
function processInput(input: string | number): string[] | number {
  if (typeof input === "string") {
    return input.split(",");
  }
  return input * 2;
}

const result1 = processInput("a,b,c"); // string[]
const result2 = processInput(5);       // number

Overloads preserve precise type relationships between inputs and outputs that unions would lose.

Key Takeaway: Use union types for flexible inputs with consistent handling; use overloads when different input types produce fundamentally different output types or behaviors.