Sub topic 8
Pitfalls: unchecked bodies, inference, and over-specific signatures
Earlier chapters showed how to write overload signatures, how the implementation signature relates to them, and how the compiler picks one. This chapter covers where overloads go wrong. Most of these problems produce no error, so you only notice them when a value at runtime does not match its type.
This chapter assumes you can read overload declarations, know that callers cannot see the implementation signature, and are comfortable with unions, literal types, generics, typeof narrowing, and Array.isArray.
Pitfall 1: The implementation body is not checked against the overloads
An overloaded function has two kinds of contract. The overload signatures are what callers rely on. The implementation is what actually runs. The compiler checks only that the two are loosely compatible. It does not check that each branch of the body produces the type promised by the overload that selected it.
What the compiler does check
For each overload, the implementation signature must be assignable to it in a loose sense. The parameters must overlap, and the return types must be related in at least one direction. If an overload asks for a parameter type the implementation cannot accept, you get an error:
function f(x: number): number;
function f(x: string): string; // Error: This overload signature is not compatible with its implementation signature.
function f(x: number): number | string {
return x;
}The implementation accepts only number, so the string overload is rejected. This check catches the obvious mismatch and nothing more.
What it does not check
Here is a function that compiles cleanly but is wrong:
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return 0; // compiles, but wrong for arrays
}
const nums = parse(["1", "2"]); // typed number[]
console.log(nums.length); // prints undefined at runtimeThe caller sees number[]. The body returns 0 for every input. The compiler accepts this because number[] and number | number[] are related, and a body returning number | number[] satisfies the implementation signature. Nothing links "the input was an array" to "the output must be an array".
A correct body can also be broken silently. This version swaps the branches and still compiles:
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
// Bug: the branches are reversed. It still compiles.
return Array.isArray(input) ? Number(input[0]) : input.length;
}The callers' types come entirely from the overload lines, and the body only has to produce some member of the union.
Defences
You cannot make the compiler verify the pairing, but you can reduce the risk:
- Keep the body small. Delegate each case to a helper with an exact signature, so the only unchecked code is a single dispatch line.
- Write runtime tests for each overload. A type test alone is not enough, because the types come from the overload lines and always pass.
- Add compile-time assertions in a test file to lock in the overload set. These catch someone editing a signature later.
const parseOne = (s: string): number => Number(s);
const parseMany = (xs: string[]): number[] => xs.map(parseOne);
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? parseMany(input) : parseOne(input);
}
// Runtime checks: these catch a wrong body.
console.assert(parse("7") === 7);
console.assert(Array.isArray(parse(["1", "2"])));
// Compile-time checks: these catch a changed overload.
const one: number = parse("7");
const many: number[] = parse(["1", "2"]);Pitfall 2: Inference sees only the last overload
Anywhere TypeScript must turn an overloaded function into a single signature, it uses the last overload signature. The implementation signature is not used, because callers cannot see it. This affects Parameters<T>, ReturnType<T>, infer in conditional types, and generic functions that take a function argument.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
type P = Parameters<typeof toArray>; // [value: number]
type R = ReturnType<typeof toArray>; // number[]The string overload does not appear in either result. A helper type built on Parameters will quietly ignore all but one signature.
The same rule applies when you pass an overloaded function to a generic helper:
function apply<A, R>(fn: (arg: A) => R, arg: A): R {
return fn(arg);
}
const ok = apply(toArray, 1); // number[]
// apply(toArray, "x"); // Error: A and R were inferred from the last overload onlyInference picked A = number and R = number[] from the last signature. The call with "x" fails even though toArray accepts strings. Assignability checks can consider every overload, but inference does not.
Two practical consequences follow:
- If you write overloads for a function that others will wrap with
ReturnTypeor similar utilities, put the signature you most want inferred last. This is usually the most general one, which already fits the "specific first, general last" ordering. - If you need type information for a particular shape, define a named type for it instead of extracting it from the overloaded function:
type StringToArray = (value: string) => string[];
type NumberToArray = (value: number) => number[];
const asStrings: StringToArray = toArray; // picks the matching overload
const asNumbers: NumberToArray = toArray;Assigning an overloaded function to a single-signature type works when any of its overloads is assignable to that type. That is why the two assignments above compile.
Pitfall 3: Order mistakes that silently shadow
The compiler tries overloads from top to bottom and uses the first one that fits. If a general signature comes before a specific one, the specific signature can never be selected. TypeScript does not report an error for this unreachable overload:
function wrap(x: unknown): unknown[];
function wrap(x: string): string[]; // never selected
function wrap(x: unknown): unknown[] {
return [x];
}
const w = wrap("a"); // unknown[], not string[]Every argument matches unknown, so the second overload is dead. The editor tooltip on wrap("a") shows which overload was chosen. Check it when you add an overload and the return type is not what you expected.
The general rule is to order signatures from most specific to least specific. When two overloads are not related by specificity, such as (x: string) and (x: number), their order does not matter for those arguments. It can still matter for union and any arguments, so check those cases.
An any argument matches the first overload, since any is assignable to everything. If a caller passes any, the result type is whatever your first overload returns. Put the overload you want as the default for loosely typed callers first among the candidates.
Pitfall 4: Literal arguments, widening, and unions
Overloads that discriminate on string literals are common. They work only when the caller's argument has a literal type. Consider this shape factory:
type Circle = { kind: "circle"; r: number };
type Square = { kind: "square"; side: number };
function make(kind: "circle", size: number): Circle;
function make(kind: "square", size: number): Square;
function make(kind: "circle" | "square", size: number): Circle | Square {
return kind === "circle" ? { kind, r: size } : { kind, side: size };
}
const c = make("circle", 2); // Circle
const s = make("square", 3); // SquareNow consider a caller whose argument has been widened:
let kind = "circle"; // type is string, because let widens the literal
// make(kind, 2); // Error: No overload matches this call.
const fixed = "circle"; // type is "circle"
make(fixed, 2); // Circle
const either: "circle" | "square" = Math.random() > 0.5 ? "circle" : "square";
// make(either, 2); // Error: a union matches neither single-literal overloadThere are two separate causes:
let kind = "circle"has typestring. Neither overload acceptsstring.- A union argument is checked against each overload as a whole.
"circle" | "square"is not assignable to"circle", and not assignable to"square".
The fix for the union case is an extra overload that accepts the union and returns the union. Place it last:
type Circle = { kind: "circle"; r: number };
type Square = { kind: "square"; side: number };
function make(kind: "circle", size: number): Circle;
function make(kind: "square", size: number): Square;
function make(kind: "circle" | "square", size: number): Circle | Square;
function make(kind: "circle" | "square", size: number): Circle | Square {
return kind === "circle" ? { kind, r: size } : { kind, side: size };
}
const either: "circle" | "square" = Math.random() > 0.5 ? "circle" : "square";
const shape = make(either, 2); // Circle | SquareThe third overload looks like it repeats the implementation signature, which is the point. The implementation signature is invisible to callers, so you restate it as a public overload when you want union callers to compile.
If the string argument is not a literal at all, for example input from a form field, no literal overload applies. Either narrow it first with a check or type guard, or add a (kind: string, ...) fallback that returns a broad type.
Pitfall 5: Over-specific overloads
It is tempting to write one overload per case. This works for two or three cases and becomes a maintenance burden after that. Each new case needs a new line in the overload list, and the list is the place where ordering mistakes happen.
Here is an event subscription function written with one overload per event name:
interface EventMap {
click: { x: number; y: number };
key: { code: string };
}
declare function on(type: "click", handler: (event: EventMap["click"]) => void): void;
declare function on(type: "key", handler: (event: EventMap["key"]) => void): void;
declare function on(type: string, handler: (event: unknown) => void): void;Adding an event means editing EventMap and adding another overload. The last signature also lets any misspelled event name through, with event typed as unknown.
A generic constrained by the keys of a map says the same thing in one signature, and a typo becomes a compile error:
interface EventMap {
click: { x: number; y: number };
key: { code: string };
}
type Handler<K extends keyof EventMap> = (event: EventMap[K]) => void;
const listeners = new Map<keyof EventMap, Array<(event: any) => void>>();
function on<K extends keyof EventMap>(type: K, handler: Handler<K>): void {
const list = listeners.get(type) ?? [];
list.push(handler);
listeners.set(type, list);
}
on("click", (e) => console.log(e.x, e.y)); // e is { x: number; y: number }
on("key", (e) => console.log(e.code)); // e is { code: string }
// on("clik", () => {}); // Error: "clik" is not a key of EventMapA single generic signature also infers the callback parameter type from the first argument, which a list of overloads handles less predictably.
A second kind of over-specificity is overloading on a type that only matters in the return type. If every overload takes the same shape of input and the output type follows from that input type, a generic is the right tool. If the arguments differ in count or in structure, overloads are appropriate. If you cannot describe in one sentence why the return type differs per overload, a union or generic probably fits better.
Smaller traps
These do not need a full section, but each has caught real code.
- Overloads must be adjacent. Putting a statement between overload lines, or between the last overload and the implementation, gives the error "Function implementation is missing or not immediately following the declaration".
- Modifiers must agree. All signatures need the same
exportanddefaultstatus. Mixingexporton some and not others is an error. - Optional parameters on the implementation hide arity bugs. In
createDate(a: number, b?: number, c?: number), the implementation accepts two arguments, but no overload does, so callers cannot make that call. The body still has to cope with the case for its own safety, and a missing check there is not detected. - Contextual typing across overloads is limited. When a callback parameter has a different type in each overload, an unannotated arrow function can end up with an implicit
anyor the wrong type. If you see this, annotate the callback parameter or restructure the signatures. - Declaration files expose only the overloads. The implementation signature is not emitted into
.d.tsoutput, so consumers of your library see exactly the overload list. A signature you forgot to add is missing for them too.
Reading "No overload matches this call"
When a call fails, TypeScript reports one message that lists each overload and why it was rejected, for example "Overload 1 of 3 ... Overload 2 of 3 ...". In older versions and some situations, the compiler instead reports only the failure of the last overload. That can mislead you into fixing the wrong signature.
A reliable way to debug is:
- Hover over the argument to see its exact type. Check for widening, such as
stringwhere you expected a literal. - Check whether the argument is a union. If so, you need an overload that accepts the union.
- Count the arguments. Overloads allow only the counts you wrote.
- Look at the order of the overloads.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Unchecked body | Type says `number[]`, runtime value is wrong | Delegate to typed helpers, write runtime tests |
| Last-signature inference | `Parameters` or `ReturnType` shows one overload; generic helper rejects valid calls | Put the preferred signature last, or define named types per shape |
| General overload first | Specific overload never chosen, broad return type | Order from most specific to most general |
| Widened literal | "No overload matches" with a `let` variable | Use `const`, `as const`, or narrow first |
| Union argument | "No overload matches" with a union | Add a final overload that accepts the union |
| One overload per case | Long list, typos accepted by a `string` fallback | Use a generic with `keyof` and a lookup type |
Exercises
Exercise
This function compiles, but the type of r is wrong at runtime. Why does the compiler accept it, and how would you catch the bug? Code: function size(x: string): number; function size(x: string[]): number[]; function size(x: string | string[]): number | number[] { return 1; } then const r = size(["a", "b"]);
Show answer
The compiler checks only that the implementation signature is loosely compatible with each overload. The body returns 1, which is a valid number | number[], and the compiler does not tie the array input to an array result. The caller sees number[] for r, but the value is 1. Catch it with a runtime test such as console.assert(Array.isArray(size(["a", "b"]))), and keep the body small by delegating to helpers with exact signatures.
Exercise
Given function toArray(value: string): string[]; function toArray(value: number): number[]; function toArray(value: string | number): (string | number)[] { return [value]; }, what are ReturnType<typeof toArray> and Parameters<typeof toArray>, and why?
Show answer
ReturnType<typeof toArray> is number[] and Parameters<typeof toArray> is [value: number]. When an overloaded function is converted to a single signature for inference, TypeScript uses the last overload signature. The implementation signature is not used because callers cannot see it.
Exercise
A caller writes let mode = "fast"; run(mode); where run has overloads run(mode: "fast"): Fast; and run(mode: "safe"): Safe;. Why does the call fail, and what are two ways to fix it?
Show answer
let widens the literal, so mode has type string, and neither overload accepts string. Fix it by declaring const mode = "fast"; so the type stays "fast", or by annotating the variable as let mode: "fast" = "fast";. If mode can be either value at runtime, add an overload run(mode: "fast" | "safe"): Fast | Safe; after the specific ones.
Exercise
You have on(type: "click", ...), on(type: "key", ...), on(type: "scroll", ...) and a final on(type: string, handler: (event: unknown) => void). Name two problems with this design and a replacement.
Show answer
The final string overload accepts misspelled event names and gives the handler an unknown event, and every new event needs another overload line. Replace the list with a generic signature on<K extends keyof EventMap>(type: K, handler: (event: EventMap[K]) => void): void backed by an EventMap interface. Typos then fail to compile and the callback parameter is inferred from the event name.