Web Analytics

Function Overloading

Intermediate~15 min

Function overloading allows you to define multiple function signatures for the same function name, providing different ways to call the function based on parameter types.

Basic Overloading

Define multiple signatures, then implement the function with a compatible signature:

Output
Click Run to execute your code
How It Works:
  1. Overload signatures - Define the different ways to call the function
  2. Implementation signature - Write the actual function body
  3. TypeScript picks the correct overload based on arguments

Why Use Overloading?

Function overloading is useful when a function can accept different parameter combinations:

  • Different parameter types: String or number input
  • Different parameter counts: 1, 2, or 3 parameters
  • Different return types: Based on input type

Overloading vs Union Types

Approach When to Use Example
Overloading Different return types based on input getValue(id: number): User
getValue(name: string): User[]
Union Types Same return type, flexible input format(value: string | number): string

Common Mistakes

1. Implementation Signature Visible to Callers

// ✗ Wrong - implementation signature is too specific
function greet(name: string): string;
function greet(name: string): string {  // Duplicate!
    return `Hello, `;
}

// ✓ Correct - use 'any' or union in implementation
function greet(name: string): string;
function greet(name: any): any {
    return `Hello, `;
}

2. Incompatible Implementation

// ✗ Wrong - implementation doesn't match overloads
function process(x: string): number;
function process(x: number): string;
function process(x: boolean): boolean {  // Error!
    return x;
}

// ✓ Correct - implementation covers all overloads
function process(x: string): number;
function process(x: number): string;
function process(x: string | number): string | number {
    return typeof x === "string" ? x.length : x.toString();
}
Important: The implementation signature is NOT visible to callers. Only the overload signatures are used for type checking.

Summary

  • Multiple signatures for different call patterns
  • One implementation that handles all cases
  • TypeScript chooses the correct overload automatically
  • Use when return type depends on parameter type

What's Next?

Next: Interface Basics to define object shapes!