Function Overloads

Several Signatures, One Body

Overloads let one function have different signatures depending on its arguments. Write the overload signatures first, then one implementation that handles all of them. Callers only see the overload signatures.

Example

function getProduct(id: number): { id: number; name: string };
function getProduct(ids: number[]): { id: number; name: string }[];
function getProduct(idOrIds: number | number[]) {
  const find = (id: number) => ({ id, name: "Product " + id });
  return Array.isArray(idOrIds) ? idOrIds.map(find) : find(idOrIds);
}

const one = getProduct(5);       // single object type
const many = getProduct([1, 2]); // array type
console.log(one.name);
console.log(many.map((p) => p.name));

Output

Product 5
[ 'Product 1', 'Product 2' ]

When Not to Use Overloads

Example

If the return type does not depend on the argument, a union parameter is simpler than overloads.

function len(x: string | unknown[]): number {
  return x.length;
}
console.log(len("hello"), len([1, 2, 3]));

Output

5 3

Tip: Prefer union parameters or optional parameters. Use overloads only when the return type changes with the input, as with getProduct above.