The Analogy: The Alterations List at a Tailor's Shop
A tailor's shop has one workroom and one pair of hands, but pinned by the counter is a printed alterations list, and that list is what a customer actually orders from. It reads down the card: "take up trousers", "take up trousers, lined", "reshape a jacket", each with its own price and its own promised turnaround. The customer names a job from the list and the assistant writes it up; the workroom then does whatever that job requires. The published list is a curated set of jobs the shop offers, each a specific shape of request with its own specific outcome, and it is the only thing the public can order from. That published list is a function's overload signatures: a handful of exact call shapes, each pairing what you bring with what you get back.
Behind the list is the workroom, and the workroom is wider than the card. The tailor can, in principle, sew almost anything, and the single process back there has to be broad enough to carry out every job the list offers plus the shared handling they have in common. But you cannot walk in and order "the workroom" directly; you order a line from the card, and the assistant matches your request to it. That back-room process is the implementation signature: one wide body that must be able to satisfy every published shape, yet is never itself the thing a caller reaches for. The dining public sees the menu, not the kitchen; the customer sees the alterations list, not the workroom.
The assistant reads the card from the top and stops at the first line that fits the garment in hand, and that reading order is not decoration -- it is behaviour. If a broad catch-all line like "any trouser job" is printed above the specific "take up trousers, lined", then a lined pair is written up at the generic rate and the specific line, with its proper price and its promised finish, is never reached. And naming more detail can route you to a firmer promise: declare that the trousers are lined and you land on a line that quotes a different, more exact outcome than the plain trouser row could. That is overload resolution -- top to bottom, first match wins -- and it is why an extra argument can change not just the price but the very shape of what comes back.
The failure mode is a line on the card that the workroom cannot actually honour. Suppose someone adds "reline a full-length coat, same day" to the list, but the workroom has no machine that can reline a coat in a day. The card now promises a job the back room cannot deliver, and the lie is only discovered when a customer orders it and comes back to nothing. In code this is the deadliest overload mistake: the compiler checks your function body against the wide implementation signature, not against each published overload, so an overload that the body does not truly satisfy still sits on the card, type-checking cleanly and lying to every caller who orders it. A published shape is a promise, and every promise on the list has to be one the single body behind it can keep.
Syntax or Core Structure
You write the overload signatures first -- bodyless lines that are the published card -- then one implementation signature with the actual body, wide enough to cover them all. Callers see only the overloads; the implementation line is not callable.
// src/reverse.ts
// overload signatures: the two published shapes
function reverse(value: string): string;
function reverse(value: string[]): string[];
// implementation signature: the wide workroom, not callable directly
function reverse(value: string | string[]): string | string[] {
return typeof value === "string"
? value.split("").reverse().join("")
: [...value].reverse();
}
const a = reverse("abc"); // typed string
const b = reverse(["x", "y", "z"]); // typed string[]
console.log(a);
console.log(b.join(" "));
console.log(a.toUpperCase()); // legal: a is string, not a union
Output:
cba
z y x
CBA
The two bodyless lines are the card: hand reverse a string and you are promised a string, hand it a string array and you are promised a string array. The third line, with the union parameter, is the workroom -- broad enough to handle either, and never called directly. Because a came through the string overload it is typed string, so a.toUpperCase() is legal with no narrowing; a single union-returning function would have typed a as a string-or-array and refused the call. reverse("abc") is "cba", reverse(["x", "y", "z"]) reverses to ["z", "y", "x"] and joins to "z y x", and the uppercase of "cba" is "CBA".
Technical Depth: The Hidden Body, Resolution Order, and Narrowing Returns
The implementation line is invisible to callers, overloads are read top to bottom so their order is behaviour, an extra argument can narrow the return type, and knowing when to reach for a generic instead keeps the card short.
The implementation signature is not on the card
Callers may only write one of the published overloads. The wide implementation line exists to give the body a type to check against, but it is not itself a call shape, so an argument that fits only the implementation is refused.
// src/hidden.ts
function tag(value: string): string;
function tag(value: number): string;
function tag(value: string | number): string {
return typeof value === "string" ? "s:" + value : "n:" + value;
}
console.log(tag("hi"));
console.log(tag(42));
// tag(true); // refused: no published overload accepts a boolean
Output:
s:hi
n:42
Output (tsc, for the commented line):
error TS2769: No overload matches this call.
Overload 1 of 2, '(value: string): string', gave the following error.
Argument of type 'boolean' is not assignable to parameter of type 'string'.
Overload 2 of 2, '(value: number): string', gave the following error.
Argument of type 'boolean' is not assignable to parameter of type 'number'.
tag("hi") matches the first overload and tag(42) the second, giving "s:hi" and "n:42". The implementation accepts string | number, but that line is the workroom, not a card entry, so tag(true) is refused with TS2769 -- and note the compiler reports why each published overload failed, not the implementation. If a boolean should work, it needs its own line on the card.
Order is behaviour: first match wins
The compiler walks the overloads top to bottom and stops at the first that fits. A broad line above a specific one swallows the call, so the specific line's return type is never chosen.
// src/resolve.ts
function badRepeat(text: string): string;
function badRepeat(text: string, times: number): string;
function badRepeat(text: string, times = 2): string {
return text.repeat(times);
}
console.log(badRepeat("ab")); // no times: the default 2 applies
console.log(badRepeat("ab", 3)); // times given: repeats 3
Output:
abab
ababab
Here the two overloads differ only in argument count and both return string, so order is harmless and the calls resolve cleanly: badRepeat("ab") takes the default times of 2 for "abab", and badRepeat("ab", 3) repeats three times for "ababab". Order turns load-bearing the moment the overloads return different types: put the widest one first there and it wins every match, the narrower lines below it become dead entries, and callers silently get the broad return type. The rule is always most specific first.
An extra argument can narrow the return
This is what a union parameter can never do: change the return type based on which arguments were passed. Passing a fallback removes the null from the result.
// src/store.ts
class Store {
private data: Record<string, string> = { theme: "dark" };
get(key: string): string | null;
get(key: string, fallback: string): string;
get(key: string, fallback?: string): string | null {
return this.data[key] ?? fallback ?? null;
}
}
const s = new Store();
const maybe = s.get("theme"); // typed string | null
const sure = s.get("missing", "light"); // typed string, never null
console.log(maybe ?? "none");
console.log(sure.toUpperCase()); // legal: sure cannot be null
Output:
dark
LIGHT
Called with one argument, get promises string | null, so maybe must be guarded and maybe ?? "none" prints the stored "dark". Called with a fallback, the second overload promises a plain string, so sure is known non-null and sure.toUpperCase() needs no guard; the missing key falls back to "light", which uppercases to "LIGHT". The presence of the fallback argument changed the shape of what comes back -- the exact relationship overloads exist to capture.
When a generic is the better tool
Overloads earn their keep when the return shape changes with the arguments. When the return is simply "whatever element type came in", a single generic is shorter and needs no card to maintain.
| Approach | Reach for it when |
|---|---|
| Union parameter | the behaviour and return type are the same for every input |
| Generic | the return type is just a function of the input type |
| Overloads | different argument counts or combinations give structurally different returns |
| Discriminated options object | the variants are many and a positional card would be unreadable |
A first<T>(xs: T[]): T | undefined needs no overloads because the return simply follows the element type; three overloads for string, number, and boolean arrays would say the same thing at three times the length. Reach for the card only when the relationship is genuinely irregular.
Real World Example: A Consignment Pricer That Narrows on Insurance
A parcel depot quotes carriage on outbound consignments. An ordinary consignment gets a single charge; an insured one gets a richer quote with both a charge and a cover figure. The overload pair lets one price function hand back a plain number for the ordinary case and a structured object for the insured case, and the report loop picks the right shape per row.
// src/pricer.ts
interface Insured {
charge: number;
cover: number;
}
function price(weight: number): number;
function price(weight: number, insured: true): Insured;
function price(weight: number, insured?: true): number | Insured {
if (insured) {
return { charge: weight * 10 + 50, cover: weight * 100 };
}
return weight * 10;
}
interface Consignment {
ref: string;
weight: number;
insured: boolean;
}
const CONSIGNMENTS: readonly Consignment[] = [
{ ref: "A1", weight: 3, insured: false },
{ ref: "B2", weight: 5, insured: true },
{ ref: "C3", weight: 2, insured: false },
{ ref: "D4", weight: 4, insured: true },
];
function pad(text: string, width: number): string {
return text.padEnd(width);
}
const report: string[] = [];
report.push(pad("REF", 6) + pad("WEIGHT", 8) + pad("CHARGE", 8) + "COVER");
let chargeTotal = 0;
let coverTotal = 0;
for (const c of CONSIGNMENTS) {
if (c.insured) {
const quote = price(c.weight, true); // typed Insured
chargeTotal += quote.charge;
coverTotal += quote.cover;
report.push(pad(c.ref, 6) + pad(String(c.weight), 8) + pad(String(quote.charge), 8) + String(quote.cover));
} else {
const quote = price(c.weight); // typed number
chargeTotal += quote;
report.push(pad(c.ref, 6) + pad(String(c.weight), 8) + pad(String(quote), 8) + "n/a");
}
}
const insuredCount = CONSIGNMENTS.filter((c) => c.insured).length;
console.log("consignments: " + CONSIGNMENTS.length + ", insured: " + insuredCount);
console.log(report.join("\n"));
console.log("charge total: " + chargeTotal);
console.log("cover total: " + coverTotal);
Output:
consignments: 4, insured: 2
REF WEIGHT CHARGE COVER
A1 3 30 n/a
B2 5 100 500
C3 2 20 n/a
D4 4 90 400
charge total: 240
cover total: 900
The two overloads are the whole point of the design. The loop reads c.insured and takes one of two branches: the insured branch calls price(c.weight, true), which matches the second overload and returns an Insured, so quote.charge and quote.cover are both known to exist; the ordinary branch calls price(c.weight), which matches the first overload and returns a plain number, so quote is added directly and the cover cell prints n/a. A union return type of number | Insured on a single signature could not do this -- every caller would have to test the result at runtime before reading .charge, even on the rows that are certainly insured.
Trace the figures against the overload bodies. A1 weighs 3 and is ordinary, so its charge is 3 * 10, which is 30. B2 weighs 5 and is insured, so its charge is 5 * 10 + 50, which is 100, and its cover is 5 * 100, which is 500. C3 weighs 2 ordinary for 20, and D4 weighs 4 insured for a charge of 4 * 10 + 50, which is 90, and a cover of 400. The charge column sums to 30 + 100 + 20 + 90, which is 240, and the two cover figures sum to 500 + 400, which is 900; the two ordinary rows contribute no cover, so the cover total counts only the insured pair.
The design has real limits worth naming. The most concrete flaw is the insured: true literal: there is no overload for insured: false, so a caller holding a plain boolean variable cannot write price(w, flag) at all -- neither published signature accepts a boolean, and the code is forced into the manual if (c.insured) branch you see here rather than passing the flag straight through. A cleaner design would either add a price(weight: number, insured: false): number overload or drop overloads entirely for a single signature that returns a discriminated result. The second limit is honesty: the implementation returns number | Insured, and TypeScript checks the body only against that wide signature, never against the two narrow overloads, so if the insured branch mistakenly returned a bare number the overloads would still promise callers an Insured and the lie would surface only at runtime. Overloads move the burden of keeping the promises onto the author.
Common Mistakes
- Trying to call the implementation signature directly. The wide implementation line exists only to type the body; it is not a published call shape. Arguments that fit only the implementation, such as passing a
booleanwhere the overloads accepttrue, are refused with TS2769.
- Listing the broad overload above the specific one. Resolution walks top to bottom and stops at the first match, so a wide signature placed first swallows calls the narrower one below was meant to catch, and the narrower return type is never chosen.
- Writing an implementation signature narrower than an overload. The body's parameters and return type must accept everything the overloads promise. If an overload takes
string[]but the implementation only takesstring, TypeScript rejects the overload as incompatible.
- Believing the body is checked against the overloads. The body is checked only against the implementation signature. A branch that returns the wrong shape for a given overload compiles silently, so keeping each overload's promise is the author's responsibility, not the compiler's.
- Reaching for overloads when a union parameter suffices. If every input produces the same behaviour and the same return type, one signature with a union parameter is shorter and clearer than two overloads that return the same thing.
- Reaching for overloads when a generic is the right tool. When the return type is simply the input's element type, a single generic like
<T>(xs: T[]): Tsays it once, whereas three type-specific overloads repeat the same relationship three times.
- Counting the implementation signature as a public overload. Callers never see it and cannot invoke it, so it is not one of the ways to call the function; only the signatures written above the body are.
- Forgetting the implementation must come last. The overload signatures are written first and the single implementation with its body comes last. Interleaving them, or writing overloads with no implementation, is a syntax error.
- Overloading to fake behaviour a default parameter handles. Two overloads that differ only by a trailing argument and share a return type are usually better written as one signature with a default value, which needs no second card at all.
Best Practices
- Order overloads most specific first. Because resolution stops at the first match, put the tightest signatures at the top and the broadest acceptable one last, so each call lands on the return type you intended.
- Keep the implementation signature wide and private. Make its parameters and return type the union of every overload's, and treat it purely as the body's contract rather than as a call shape callers are meant to use.
- Prefer a union parameter when nothing varies. If the return type and behaviour are identical across inputs, one signature with a union parameter beats a stack of overloads that all return the same thing.
- Prefer a generic when the return follows the input. When the result type is a function of the argument type, a single generic signature is shorter and needs no edits as new element types appear.
- Prefer an options object for many variants. Once the combinations grow past two or three, one signature taking a discriminated options object stays readable where a tower of positional overloads becomes a puzzle.
- Return the union of all overload returns from the body. Type the implementation's return as the widest shape any branch can produce so the body type-checks, then let each overload narrow that shape for callers.
- Keep the overload list short. Every overload is a line a caller must scan; two or three chosen shapes communicate clearly, while a dozen is a design smell pointing toward a generic or an options object.
- Document each overload's intent. A one-line comment above each signature saying when a caller should reach for it turns a cryptic stack of shapes into a usable menu.
Practice Exercises
- Add an express tier. Extend
pricewith a third overloadprice(weight: number, insured: true, express: true): Insuredwhose charge adds a flat30, place it in the correct position, and confirm the two-argument insured call still resolves to the right return type.
- Convert a union into overloads. Take a
describe(value: string | number): stringthat returns differently shaped strings per input type and split it into two overloads; observe which callers now receive a narrower return type than the union gave them.
- Build a typed parser. Write
parse(kind: "int", text: string): numberandparse(kind: "str", text: string): stringoverloads over one implementation, and show that the return type follows the literalkindargument passed at the call site.
- Fix the false-insured gap. The pricer has no overload for an explicit
insured: false, so a caller holding abooleancannot pass it through. Add that overload, or refactor to a single boolean-discriminated signature, and note the tradeoff between the two fixes.