Function Overloads — TypeScript

A function overload gives one function several signatures (lines with the parameter types and the return type, no body), so the result type follows the input…

The menu board at a food stall says: "order one number, get one plate. Order several numbers, get a tray." Customers only read the menu board, and from the board alone they know what they'll be handed. The kitchen that actually cooks is out of sight.

A function overload gives one function several signatures. A signature is one line with the function's name, its parameter types and its return type, with no body. Each signature is one pair of "if this goes in, that comes out", like one line on the menu board. So the menu board is the list of signatures, and the customer is the caller (the code that calls the function). The kitchen is the implementation: the function with its body, the code that actually runs.

The problem with a union alone

Our stall has three items. The item number is the array index: 0 is Coffee and 2 is Bread. The function order takes one number or a list of numbers, and returns the item names:

const MENU = ["Coffee", "Tea", "Bread"];

function order(choice: number | number[]): string | string[] {
  if (Array.isArray(choice)) {
    return choice.map((n) => MENU[n]); // a list of numbers, a list of names
  }
  return MENU[choice]; // one number, one name
}

const result = order(0); // result: string | string[]
result.toUpperCase();

Before you look at the answer below, take a guess: does TypeScript accept that last line, result.toUpperCase(), or reject it?

error TS2339: Property 'toUpperCase' does not exist on type 'string | string[]'.
  Property 'toUpperCase' does not exist on type 'string[]'.

TypeScript rejects it. You know order(0) always returns one string, but the type of result only says "a string or an array of strings". With a union value, TypeScript only allows what works on every member, and an array has no .toUpperCase(). The fact "one number in, one name out" is lost in the union.

Writing an overload

An overload keeps the fact "one number in, one name out". First write the signatures for callers, then one implementation at the very bottom:

const MENU = ["Coffee", "Tea", "Bread"];

// Overload signatures: for callers, no body
function order(choice: number): string;
function order(choice: number[]): string[];
// Implementation: the only one with a body
function order(choice: number | number[]): string | string[] {
  if (Array.isArray(choice)) {
    return choice.map((n) => MENU[n]);
  }
  return MENU[choice];
}

const one = order(0);      // one: string
const two = order([0, 2]); // two: string[]
one.toUpperCase();         // "COFFEE", allowed now
two.join(", ");            // "Coffee, Bread"
Call Matching overload Result type Value at run time
order(0) (choice: number): string string "Coffee"
order([0, 2]) (choice: number[]): string[] string[] ["Coffee", "Bread"]
order("0") none error refused before it runs

This is the error message for order("0"):

error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'number[]'.

After compiling, the overload signatures are all gone. JavaScript has just one function order, the implementation. So overloads are used only for type checking.

The rules for writing them

When a union is enough

Overloads help when the result type (the output) depends on the input type: one number gives one string, a list of numbers gives a list of strings. When the result type is always the same whatever goes in, a plain union is enough and shorter:

function getLength(value: string | number[]): number {
  return value.length; // strings and arrays both have a length
}

getLength("word");    // 4
getLength([1, 2, 3]); // 3

The output is always number, so nothing is lost. A practical rule: if the output type differs for each input type, use an overload. If the output type is the same for every input, use a union.

⚠️ The wrong order, and overloads you don't need

TL;DR: A function overload gives one function several signatures (lines with the parameter types and the return type, no body), so the result type follows the input type. For example, order(0) is a string, and order([0, 2]) is a string[]. Write all the overload signatures first (no body, ending with a semicolon). Then write one implementation (the function with its body) at the bottom, whose types cover all those signatures. Callers only see the overloads, not the implementation. TypeScript uses the first overload that fits, so put the specific ones on top. After compiling, the overloads are gone. When the output type is the same for every input, a plain union is enough.

⚡ A union alone loses the information

Write:

function order(choice: number | number[]): string | string[] {
  if (Array.isArray(choice)) {
    return choice.map((n) => MENU[n]);
  }
  return MENU[choice];
}

const result = order(0);
result.toUpperCase();
Guess first: MENU is an array of item names, so order(0) returns one name. Is the last line accepted or rejected?

Rejected. The type of result is only string | string[], and an array has no .toUpperCase(). The fact "one number in, one name out" is lost in the union.

Meaning: You know order(0) always returns one piece of text, but the return type string | string[] doesn't keep that fact.

⚡ Signatures first, implementation at the bottom

Write:

function order(choice: number): string;
function order(choice: number[]): string[];
function order(choice: number | number[]): string | string[] {
  if (Array.isArray(choice)) {
    return choice.map((n) => MENU[n]);
  }
  return MENU[choice];
}

const one = order(0); // one: string

Meaning: A function overload gives one function several signatures: lines with the parameter types and the return type, no body. The first two lines are overload signatures, ending with a semicolon. All overload signatures come before the implementation (the function with its body), and the implementation at the bottom must have types that cover them all. Put the implementation on top and TypeScript reports an error. Callers only see the overloads, and TypeScript uses the first one that fits, so order(0) is a string.

⚡ When a union is enough

Write:

function getLength(value: string | number[]): number {
  return value.length;
}

Meaning: getLength always returns a number, so no information is lost. A practical rule: if the output type differs for each input type, use overloads. If the output type is the same for every input, use a union.

What you will learn