Sub topic 8
Overloads for functions with several call shapes
This chapter assumes you can annotate parameters and return types, write union types, and use optional parameters. It also assumes you can read a function type such as (value: string) => number. Overloads build on all three.
The problem overloads solve
Some functions accept different kinds of arguments, and the return type depends on which kind was passed. A union type describes the inputs but loses that relationship:
function toArrayLoose(value: string | number): (string | number)[] {
return [value];
}
const a = toArrayLoose("x"); // (string | number)[]
a[0].toUpperCase(); // error: Property 'toUpperCase' does not exist on type 'string | number'The caller passed a string and wants a string[]. The union signature cannot say "string in, string array out, number in, number array out". An overloaded function can say that.
Anatomy of an overloaded function
An overloaded function has two parts:
- One or more overload signatures. Each is a function header with no body, and each describes one way to call the function.
- One implementation, which has a body and handles every case.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const a = toArray("x"); // string[]
const b = toArray(1); // number[]The compiler checks each call against the overload signatures only. The implementation signature is not visible to callers:
// toArray(true);
// error: No overload matches this call.Even though the implementation accepts string | number, you cannot call toArray with a value of that union type either:
declare const input: string | number;
// toArray(input);
// error: No overload matches this call.TypeScript tries each overload separately. A union argument matches neither string nor number alone. If you want to support union arguments, add a third overload that accepts the union:
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
declare const input: string | number;
const c = toArray(input); // (string | number)[]How the compiler picks an overload
When you call an overloaded function, the compiler goes through the overload signatures from top to bottom. It uses the first one whose parameters accept the arguments, and it reports an error if none does.
The order therefore matters. Put the most specific signatures first and the most general ones last.
// Wrong order: the general signature shadows the specific one.
function wrapBad(value: unknown): unknown[];
function wrapBad(value: string): string[];
function wrapBad(value: unknown): unknown[] {
return [value];
}
const bad = wrapBad("hi"); // unknown[] (the first overload already matched)
// Right order: specific first.
function wrap(value: string): string[];
function wrap(value: unknown): unknown[];
function wrap(value: unknown): unknown[] {
return [value];
}
const good = wrap("hi"); // string[]
const other = wrap(42); // unknown[]Overloads with different argument counts
Overloads are also a way to describe calls that differ in how many arguments they take, and each shape can have its own return type or meaning.
function createDate(timestamp: number): Date;
function createDate(year: number, month: number, day: number): Date;
function createDate(yearOrTimestamp: number, month?: number, day?: number): Date {
if (month === undefined || day === undefined) {
return new Date(yearOrTimestamp);
}
return new Date(yearOrTimestamp, month - 1, day);
}
const fromStamp = createDate(0);
const fromParts = createDate(2026, 11, 25);
// createDate(2026, 11);
// error: No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.The implementation makes month and day optional because the first overload does not pass them. The overloads still rule out the two-argument call. A single signature with optional parameters would have allowed it. This is a good reason to use overloads: they can forbid combinations that optional parameters would permit.
The implementation must be compatible
Each overload signature must be compatible with the implementation signature. The check is loose. It only requires that the signatures can be reconciled, which usually means the implementation's parameters are wide enough and its return type covers every overload's return type.
// function double(x: string): string;
// function double(x: number): number;
// function double(x: string): string {
// return x + x;
// }
// error: This overload signature is not compatible with its implementation signature.In that sketch the implementation does not accept a number, so the second overload cannot be satisfied. The fix is to widen the implementation:
function double(x: string): string;
function double(x: number): number;
function double(x: string | number): string | number {
return typeof x === "string" ? x + x : x * 2;
}
const s = double("ab"); // string
const n = double(4); // numberOverloads in classes and call signatures
Methods can be overloaded in the same way. Place the overload signatures directly above the implementation inside the class:
class Store {
private data = new Map<string, string>();
get(key: string): string | undefined;
get(key: string, fallback: string): string;
get(key: string, fallback?: string): string | undefined {
return this.data.get(key) ?? fallback;
}
set(key: string, value: string): void {
this.data.set(key, value);
}
}
const store = new Store();
const maybe = store.get("theme"); // string | undefined
const sure = store.get("theme", "dark"); // stringHere the number of arguments decides whether the result can be undefined. A caller who supplies a fallback gets a plain string and does not need a check.
Overloads can also be written as several call signatures in an object type or interface:
interface Parser {
(input: string): number;
(input: string[]): number[];
}The same top-to-bottom resolution rule applies. Assigning a value to such a type is harder than calling it, because the value must satisfy every signature. The usual way to build one is a function declaration with overloads, as shown earlier.
Choosing between a union, overloads and a generic
Overloads are not always the best tool. Work through these questions in order:
| Situation | Better choice |
|---|---|
| The return type is the same whatever the argument type | A union parameter |
| The return type is a function of the argument type, such as returning the same type back | A generic signature |
| Different argument types give unrelated return types | Overloads |
| Different argument counts give different return types, or some counts must be forbidden | Overloads |
| One extra argument is simply optional and the return type does not change | An optional parameter |
For example, a function that only reports a length needs no overload:
function size(value: string | unknown[]): number {
return value.length;
}A function that returns its input's type is better as a generic:
function firstOf<T>(items: T[]): T | undefined {
return items[0];
}Our toArray could also be written generically as toArray<T extends string | number>(value: T): T[]. That is shorter, and it keeps literal types, so toArray("x") has type "x"[]. It also accepts a union argument without an extra overload. Overloads give you more control, such as the exact return types, but they cost more lines and more places to make mistakes.
Common errors
- "No overload matches this call." The arguments fit none of the signatures. Check whether you passed a union value, which needs its own overload.
- "This overload signature is not compatible with its implementation signature." The implementation is too narrow. Widen its parameter types or return type.
- A call returns a vaguer type than expected. A general overload sits above a specific one. Reorder them.
- "Function implementation is missing or not immediately following the declaration." Overload signatures must be adjacent to each other and to the implementation, with nothing between them.
- Overloads that differ only in a callback's parameter types. These are hard to read and often better handled with a generic. Resolution order can also surprise you here.
Exercise
A function format should return string when given a number, and string[] when given a number[]. Write the overloads and an implementation. Then explain why calling format with a value of type number | number[] fails, and how you would allow it.
Show answer
```
Because the answer needs code, here is a corrected version of the exercise.
Exercise
Write overloads for a function format that returns a string when given a number and a string[] when given a number[]. Why does calling it with a value of type number | number[] fail, and how do you fix that?
Show answer
Use overloads function format(value: number): string; and function format(value: number[]): string[];, followed by an implementation with signature function format(value: number | number[]): string | string[] that checks Array.isArray(value) and formats each element or the single number. A call with a number | number[] argument fails because the compiler tries each overload separately, and the union fits neither one. Add a third overload function format(value: number | number[]): string | string[]; above the implementation to accept the union.