Sub topic 4
How the Compiler Picks an Overload
What you need before this chapter
This chapter assumes you can write overload signatures followed by an implementation signature. You should also know unions, literal types, and basic generics. This chapter covers what happens at a call site: which signature the compiler picks, in what order it looks, and why it sometimes picks one you did not expect.
The selection rule
When you call an overloaded function, the compiler does not weigh the overloads against each other or look for the "best" one. It uses a simple procedure:
- Take the overload signatures in the order you wrote them. The implementation signature is not in this list.
- For each signature, check whether the call can be made with it. This means the argument count fits and every argument is assignable to its parameter type.
- The first signature that passes is the one used. Its return type becomes the type of the call expression.
- If no signature passes, the call is an error.
Most overload bugs follow from step 3. A signature that comes earlier and accepts too much will shadow every later signature that is more precise.
Tracing a call
Here is a small function with two overloads. The comments show what the compiler concludes for each call.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const a = toArray("x"); // overload 1 fits: string[]
const b = toArray(1); // overload 1 rejects number, overload 2 fits: number[]For toArray(1), the compiler tries overload 1 first. The argument 1 is not assignable to string, so it moves on. Overload 2 accepts it, so the result is number[]. The implementation signature (string | number) is never considered, even though it would also accept 1.
| Call | Overload 1 `(string)` | Overload 2 `(number)` | Result |
|---|---|---|---|
| `toArray("x")` | accepted | not tried | `string[]` |
| `toArray(1)` | rejected | accepted | `number[]` |
| `toArray(true)` | rejected | rejected | error |
Argument count comes first
A signature is only a candidate if the number of arguments fits. The compiler counts required parameters, optional parameters, and rest parameters. A signature with two required parameters cannot accept a call with one argument, no matter what the types are.
function createDate(timestamp: number): Date;
function createDate(year: number, month: number, day: number): Date;
function createDate(a: number, b?: number, c?: number): Date {
if (b === undefined || c === undefined) {
return new Date(a);
}
return new Date(a, b - 1, c);
}
createDate(0); // overload 1
createDate(2026, 11, 25); // overload 2
// createDate(2026, 11); // Error: no overload takes exactly two argumentsThe implementation uses optional parameters, so it would accept two arguments. Callers cannot use that. The overload list is the whole public contract, and the two-argument call matches neither signature.
Arity filtering also affects order. Suppose one overload takes (x: string) and another takes (x: string, y?: number). A one-argument call satisfies both, so the first one listed wins. If both return the same type, the order does not matter. If they return different types, you probably wanted a single signature with an optional parameter instead.
Order matters: specific before general
Because the first match wins, you must list the most specific signatures first. Here is the correct order.
function pick(x: string): string;
function pick(x: unknown): unknown;
function pick(x: unknown): unknown {
return x;
}
const s = pick("hi"); // string, matched by the first overload
const u = pick(42); // unknown, matched by the second overloadNow reverse the two signatures and see what happens.
function pickReversed(x: unknown): unknown;
function pickReversed(x: string): string;
function pickReversed(x: unknown): unknown {
return x;
}
const t = pickReversed("hi"); // unknown, not stringEvery value is assignable to unknown, so the first signature accepts every call. The string overload can never be chosen. The compiler does not report an error for this, so the only symptom is a return type that is less precise than you intended.
Subtype overlaps
The same problem appears with object types, where one type is a subtype of another. A Person has everything a Named has, so a Person value is assignable to a Named parameter.
interface Named {
name: string;
}
interface Person extends Named {
age: number;
}
// Wrong order: Named is more general, so it shadows the Person overload.
function describeWrong(x: Named): string;
function describeWrong(x: Person): string[];
function describeWrong(x: Named | Person): string | string[] {
return "age" in x ? [x.name, String(x.age)] : x.name;
}
// Right order: the narrower type comes first.
function describe(x: Person): string[];
function describe(x: Named): string;
function describe(x: Named | Person): string | string[] {
return "age" in x ? [x.name, String(x.age)] : x.name;
}
const person: Person = { name: "Ada", age: 36 };
const w = describeWrong(person); // string, although the body returns string[]
const d = describe(person); // string[]
const n = describe({ name: "Bob" }); // stringdescribeWrong(person) is typed as string, but at runtime it returns an array. This is a type that lies about the value. The rule is the same as before: put the signature whose parameter type is the subtype first.
A good order to follow is:
- Literal types and other exact types.
- Narrow object types and tuples.
- Wider types such as
string,number, or a broad interface. - Catch-alls such as
unknown,any, or a bare genericT.
Literal arguments and widening
Overloads on string literal types are common, because they let a first argument decide the types of the rest. The standard library's document.createElement works this way. Here is a small version with an event registry.
const handlers = new Map<string, (...args: any[]) => void>();
function on(event: "resize", handler: (width: number, height: number) => void): void;
function on(event: "key", handler: (code: string) => void): void;
function on(event: string, handler: (...args: any[]) => void): void;
function on(event: string, handler: (...args: any[]) => void): void {
handlers.set(event, handler);
}
on("resize", (width, height) => {
console.log(width.toFixed(0), height.toFixed(0)); // width and height are number
});
on("key", (code) => {
console.log(code.toUpperCase()); // code is string
});
on("custom", (payload) => {
console.log(payload); // payload is any, from the catch-all overload
});Three things happen here.
"resize"is only assignable to the literal type"resize"and tostring. The first overload accepts it, so the compiler never looks further."custom"is rejected by the first two overloads, because it is not equal to either literal. The third overload accepts any string.- The third overload has the same shape as the implementation signature. That is allowed. Writing it again as an overload is what makes it visible to callers.
The `let` trap
Literal overloads only work when the argument has a literal type. A variable declared with let has the widened type string.
const fixed = "resize";
let loose = "resize";
on(fixed, (width, height) => {
console.log(width.toFixed(0), height.toFixed(0)); // matches overload 1
});
on(loose, (a, b) => {
console.log(a, b); // a and b are any: loose is string, so overload 3 matched
});The const declaration keeps the type "resize", so overload 1 matches. The let declaration widens the type to string, so overloads 1 and 2 reject it and overload 3 matches. If your catch-all overload were missing, the second call would be an error instead. That is often the better outcome, because it exposes the widening.
Callbacks and contextual typing
In the on example, the parameters width and height have no annotations, yet they get types. This is contextual typing: the compiler infers a lambda's parameter types from the parameter type of the signature it is being checked against.
With overloads, there is a subtlety. The compiler cannot know which signature supplies the context until it has chosen one. In practice it checks the arguments that do not depend on context first, such as the literal "resize". It then uses the candidate signature to type the lambda. If the lambda fails against that candidate, the compiler moves on to the next candidate and types the lambda again from scratch.
This explains why putting the discriminating argument first works well. The literal narrows the candidates, and the lambda is typed against the right one. If the discriminating value came after the callback, the compiler could still choose correctly, but error messages get harder to read.
Be careful when two overloads differ only in their callback parameter types. For example, (cb: (x: string) => void) and (cb: (x: number) => void) give an unannotated lambda no way to pick between them. The first signature supplies the context, so the lambda's parameter is typed string, and code written for number fails. Give the lambda an annotation, or add a distinguishing argument.
Generic overloads: inference runs per candidate
When an overload is generic, the compiler infers the type parameters separately for each candidate. A failed inference on one candidate does not affect the next.
function wrap<T>(x: T[]): T;
function wrap<T>(x: T): T[];
function wrap(x: unknown): unknown {
return Array.isArray(x) ? x[0] : [x];
}
const first = wrap([10, 20]); // number: overload 1 with T = number
const list = wrap("a"); // string[]: overload 1 fails, overload 2 with T = stringFor wrap("a"), overload 1 needs a T[], and a string is not an array, so the compiler discards that candidate. Overload 2 infers T as string and returns string[].
The order is again critical. A bare T accepts anything, so it must come last. If you swap the two signatures, wrap([10, 20]) matches T with T = number[] and returns number[][]. The array overload becomes unreachable.
When no overload matches
A call that fits none of the signatures is an error, even when the implementation signature would accept it. The most common case is passing a union to overloads that each handle one member.
declare const v: string | number;
// Error: No overload matches this call.
// toArray(v);The compiler checks string | number against overload 1, and it is not assignable to string. It then checks overload 2, and it is not assignable to number. A union is only assignable to a parameter if every member is. Neither overload handles both, so the call fails. The compiler does not split the union and try each branch separately.
The error message lists every candidate it tried:
No overload matches this call.
Overload 1 of 2, '(value: string): string[]', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Overload 2 of 2, '(value: number): number[]', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'number'.The fix is to add a signature that accepts the union. Because order decides, it goes last, after the precise signatures.
function toArrayFixed(value: string): string[];
function toArrayFixed(value: number): number[];
function toArrayFixed(value: string | number): (string | number)[];
function toArrayFixed(value: string | number): (string | number)[] {
return [value];
}
declare const input: string | number;
const p = toArrayFixed("x"); // string[]
const q = toArrayFixed(2); // number[]
const r = toArrayFixed(input); // (string | number)[]If you placed the union signature first, toArrayFixed("x") would match it and return (string | number)[], losing the precision you added overloads for.
How to read an overload error
The "No overload matches this call" message can be long. Here is how to read it.
- Each "Overload N of M" block tells you why that specific candidate rejected the call. Read them all before changing anything.
- If every block complains about the same argument, that argument's type is wrong or too wide, and you probably need a new signature.
- If different blocks complain about different arguments, the call may be a mix of two shapes that you meant to keep separate. Check the call before changing the signatures.
- If a block says that arguments were expected in a different number, the arity filter rejected that candidate before any type was compared.
A checklist for predicting the result
Use these steps when you are unsure which overload a call will match.
- Write down the type of each argument as the compiler sees it. A
letstring isstring, and aconststring is a literal. An object literal assigned to a variable has a widened property type. - Walk through the overloads in source order. Skip the implementation signature.
- For each overload, check the argument count, then check each argument for assignability.
- Stop at the first overload that passes. That signature's return type is the type of the call.
- If a later overload looks like a better match, check whether an earlier one is more general than you thought.
Exercise
Given the overloads below, what is the type of each of the two calls, and what single change makes both return the most precise type? function size(x: unknown[]): number; function size(x: string[]): bigint; function size(x: unknown[]): number | bigint { return x.length; } const a = size(["a", "b"]); const b = size([1, 2]);
Show answer
Both calls have type number. A string[] is assignable to unknown[], so the first overload accepts it and the string[] overload is never reached. The wrong order is the problem. Putting the string[] overload first makes size(["a", "b"]) return bigint while size([1, 2]) still falls through to number. (The implementation signature must also be able to return bigint, which the example's implementation signature declares.)
Exercise
A function has overloads for (event: "open", cb: (id: number) => void) and (event: string, cb: (...args: any[]) => void), in that order. You write let name = "open"; and then call the function with name and a lambda (id) => id.toFixed(). Which overload matches, and what is the type of id?
Show answer
The second overload matches, and id is any. The variable name is declared with let, so its type is widened to string and the literal overload rejects it. The catch-all accepts any string, and its callback is typed with any[] arguments, so id is any and id.toFixed() is not checked. Declaring name with const keeps the literal type "open" and selects the first overload, where id is number.
Exercise
You have overloads parse(input: string): number and parse(input: string[]): number[]. A caller passes a value of type string | string[] and gets "No overload matches this call". Write the extra signature that fixes this, and say where it goes in the list.
Show answer
Add parse(input: string | string[]): number | number[]; and put it after the two precise signatures. Each member of the union is handled by an earlier overload for calls with a single shape, and the new signature handles the union itself. If it came first, it would match every call, including parse("1"), and the precise return types would be lost.