TypeScript theorytheory 0/50 · 0%
Functions · medium

28. Function overloads

Multiple call signatures for one implementation.

Overloads let a function have several distinct signatures for different argument combinations, all implemented by a single function body.

ts
function parseAmount(value: string): number;
function parseAmount(value: number): number;
function parseAmount(value: string | number): number {
  return typeof value === "string" ? parseFloat(value) : value;
}

parseAmount("1.5"); // matches first signature
parseAmount(2);     // matches second signature

Only the overload signatures are visible to callers — the implementation signature (with the union) is not callable directly from outside. Overloads are most useful when the relationship between argument and return types can't be expressed with a single union signature, e.g. return type depends on which argument type was passed.

Check your understanding

  1. 1. What is visible to callers of an overloaded function?

  2. 2. When are overloads most useful?

  3. 3. How many function bodies does an overloaded function have?