TExcelTAD
Home › TypeScript › TS Function Overloads

TypeScript Function Overloads

Some JavaScript functions behave differently depending on what you pass in. A parse function might return a number when given a numeric string and an array when given a list; a createElement function returns a different type for each tag name. A single signature with unions often describes such functions too loosely. Function overloads let you declare several call signatures for one function, so each kind of call gets a precise return type.

The problem overloads solve

Consider a function that doubles either a number or a string. With a plain union signature, the caller loses information:

ts · try it yourself
function double(value: number | string): number | string {
  return typeof value === "number" ? value * 2 : value + value;
}

const n = double(21);
console.log(n.toFixed(1));
main.ts(6,15): error TS2339: Property 'toFixed' does not exist on type 'string | number'.
  Property 'toFixed' does not exist on type 'string'.

We know double(21) returns a number, but the signature only promises number | string. Overloads fix that.

Writing overloads

An overloaded function has two parts:

  1. Overload signatures — one or more declarations without a body. These are what callers see.
  2. The implementation signature — the real function with a body. Its parameters must be compatible with every overload, and it is not visible to callers.
ts · try it yourself
function double(value: number): number;
function double(value: string): string;
function double(value: number | string): number | string {
  return typeof value === "number" ? value * 2 : value + value;
}

const n = double(21);      // number
const s = double("ha");    // string

console.log(n.toFixed(1));
console.log(s.toUpperCase());
42.0
HAHA

TypeScript checks a call against the overloads from top to bottom and uses the first one that matches.

The implementation signature is hidden

A frequent surprise: a call that matches the implementation but no overload is rejected. With the overloads above, passing a value of type number | string fails:

ts · try it yourself
function double(value: number): number;
function double(value: string): string;
function double(value: number | string): number | string {
  return typeof value === "number" ? value * 2 : value + value;
}

function fromInput(input: number | string) {
  return double(input);
}
console.log(fromInput(4));
main.ts(8,17): error TS2769: No overload matches this call.
  Overload 1 of 2, '(value: number): number', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'number'.
      Type 'string' is not assignable to type 'number'.
  Overload 2 of 2, '(value: string): string', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'string'.
      Type 'number' is not assignable to type 'string'.

If that call should be allowed, add a third overload function double(value: number | string): number | string; at the end of the list.

Different numbers of parameters

Overloads can also describe different parameter lists. Here makeDate accepts either a timestamp or year/month/day:

ts · try it yourself
function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
function makeDate(a: number, month?: number, day?: number): Date {
  if (month !== undefined && day !== undefined) {
    return new Date(Date.UTC(a, month - 1, day));
  }
  return new Date(a);
}

console.log(makeDate(0).toISOString());
console.log(makeDate(2024, 2, 29).toISOString().slice(0, 10));
1970-01-01T00:00:00.000Z
2024-02-29

A call like makeDate(2024, 2) is rejected, because no overload takes exactly two arguments — even though the implementation technically could.

Overloads in methods

Class methods can be overloaded the same way:

ts · try it yourself
class Store {
  private items = new Map<number, string>([[1, "Tea"], [2, "Rice"], [3, "Soap"]]);

  find(id: number): string | undefined;
  find(ids: number[]): string[];
  find(arg: number | number[]): string | string[] | undefined {
    if (Array.isArray(arg)) {
      return arg.flatMap((id) => this.items.get(id) ?? []);
    }
    return this.items.get(arg);
  }
}

const store = new Store();
console.log(store.find(2));
console.log(store.find([1, 3, 9]));
Rice
[ 'Tea', 'Soap' ]

Overloads vs alternatives

Use When
A union parameter the return type doesn't depend on which member was passed
Optional parameters the extra arguments just tweak the behaviour
Generics the return type is directly related to the argument type (T in, T[] out)
Overloads a few distinct, unrelated call shapes with different return types

Tip: Prefer unions or generics when they are enough — they are simpler to read and to implement. Reach for overloads when you genuinely have a small number of different call patterns, like the DOM's createElement or Node's readFile.

Test yourself

Which signatures can callers of an overloaded function see?

  1. Only the implementation signature
  2. Only the overload signatures
  3. Both
  4. Neither — types are inferred

In which order does TypeScript try overload signatures?

  1. Bottom to top
  2. Most specific first, regardless of order
  3. Top to bottom, first match wins
  4. Randomly

When is a simple union parameter better than overloads?

  1. When the return type does not depend on the argument type
  2. Never
  3. When there are more than two parameters
  4. When the function is async