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.
Array.isArray(choice)checks whetherchoiceis an array. Inside itsif, TypeScript knowschoiceisnumber[], and after it,number. That's the type narrowing you already know from the Type Narrowing lesson.
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"
- The first two
function orderlines are overload signatures: they end with a semicolon and have no{ }. These two lines are the menu board, and they are the only lines callers see. - The third
function orderline is the implementation signature, the one that belongs to the implementation. Its types must cover every overload signature:number | number[]in,string | string[]out. - When you call
order(...), TypeScript tries the overloads from top to bottom and uses the first one that fits.
| 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
- Every overload signature comes before the implementation, one after another, with the implementation right below them. Put the implementation on top and TypeScript reports an error:
Function implementation is missing or not immediately following the declaration.(ts(2391)). - The implementation must fit every overload. Say you add
function order(choice: boolean): string;while the implementation only takesnumber | number[]. The result is the errorThis overload signature is not compatible with its implementation signature.(ts(2394)). - The implementation signature can't be called from outside. Callers only see the overload signatures. So an argument of type
number | number[]is refused, because it fits none of the overloads. - Specific on top, general below. A general overload accepts more types than a specific one. TypeScript stops at the first overload that fits, so a general overload written first hides the overloads under it.
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
- Writing the implementation first. Overload signatures on top, the implementation at the bottom. In the opposite order you get ts(2391).
- Passing a union value to an overloaded function. Inside
function orderFrom(picked: number | number[]), the callorder(picked)is refused withNo overload matches this call.If you really need it, add a third overload:function order(choice: number | number[]): string | string[];. - A general overload above a specific one. With
function label(x: number | string): string;and thenfunction label(x: number): number;, the result of the calllabel(5)has typestring. The second overload is never used. - Overloads when the output is the same. Three overloads that all return
stringcan be replaced by one union.
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.