TypeScript ยท Chapter 20 of 44

TypeScript Function Overloads

Function overloads let you describe a function that can be called in multiple different ways, each with different parameter types or counts, while still having one actual implementation.

You write several overload signatures above the real function body. TypeScript uses these signatures to check calls, while the final implementation signature must be general enough to handle every overload.

Syntax
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
  return a + b;
}

Writing overload signatures

Each overload signature declares a specific combination of parameter types and a return type, without a function body. They appear directly above the implementation.

The implementation signature

The final function definition contains the actual logic and must accept every possible combination of parameters described by the overloads, often using union types internally.

Example 1 (typescript)
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
  return a + b;
}
console.log(combine(1, 2));
console.log(combine("a", "b"));
Output
3
ab

TypeScript picks the matching overload based on the argument types used at each call site.

Example 2 (typescript)
function makeArray(x: number): number[];
function makeArray(x: string): string[];
function makeArray(x: any): any {
  return [x, x, x];
}
console.log(makeArray(5));
console.log(makeArray("hi"));
Output
[ 5, 5, 5 ]
[ 'hi', 'hi', 'hi' ]

Each overload tells callers exactly what return type to expect for a given input type.

Key points

  • Overloads let a single function support multiple call signatures.
  • Overload signatures are written above the actual implementation.
  • The implementation signature must cover every overload's parameter types.
  • Callers see only the specific overloads, not the general implementation signature.
๐Ÿ’ก Note: Overloads are useful, but often a single well-designed union parameter type is simpler.

๐Ÿ“ Quick Quiz

1. What do function overloads let you describe?

2. Where do overload signatures appear relative to the implementation?

3. What must the implementation signature handle?