Course contentsShow
← TypeScript
Lesson 275 of 1,7966. FunctionsFree lesson

Overloading by Parameter Type

Writing overloads where parameter types change the return type or behavior.

Overloading by Parameter Type

You'll learn how to create function overloads where different input types produce different return types or behaviors.

The Core Idea

Sometimes a function needs to behave differently based not just on how many parameters it receives, but on what type those parameters are. With function overloads, you can declare that when your function receives a string, it returns one type, but when it receives a number, it returns something completely different. TypeScript will track which overload you're using and enforce the correct return type automatically.

Think of it like a vending machine with different slots: insert a coin and you get candy; insert a card and you get a receipt. Same machine, different behavior based on input type.

How It Works

You write multiple overload signatures, each specifying a different parameter type and its corresponding return type. The implementation must handle all these cases:

// Overload signatures
function process(input: string): string[];
function process(input: number): boolean;

// Implementation signature
function process(input: string | number): string[] | boolean {
  if (typeof input === 'string') {
    return input.split('');
  } else {
    return input > 0;
  }
}

const result1 = process("hello");  // Type: string[]
const result2 = process(42);        // Type: boolean

TypeScript knows result1 is string[] and result2 is boolean—no union type confusion!

Why This Matters

Without overloads, the return type would be string[] | boolean for both calls, forcing you to narrow the type yourself. Overloading by parameter type gives you precision: different inputs guarantee different outputs.

Key Takeaway: Overloading by parameter type lets you declare that specific input types produce specific return types, giving you type safety without manual narrowing.