Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Function Overloads: Syntax, Signatures, and Implementation

Overload resolution order, why the implementation signature is invisible to callers, the union-argument rejection, and when a generic signature is shorter.

~6 min readTypeScript
#TypeScript#Functions#Type System
3D illustration of multiple call signature input slots channeling into a unified implementation engine

A function overload is a set of call signatures written above one implementation. The signatures are what callers see and what the checker resolves against; the implementation is a single body that must be wide enough to accept all of them and is invisible from the outside. Nearly every overload bug comes from forgetting that split — either the implementation signature leaks into the call surface as a too-permissive catch-all, or a signature is ordered after a broader one and can never be reached.

Quick Summary

  • Overload signatures plus one implementation signature form the whole construct; only the signatures are callable, and the implementation signature is never part of the public type.
  • Resolution is top to bottom and first match wins, so specific signatures must precede general ones.
  • The implementation must be compatible with every signature, or TS2394: This overload signature is not compatible with its implementation signature is reported on the offending signature.
  • Return types do not participate in resolution; two signatures that differ only in return type are a compile error.
  • Overloads do not accept a union argument: f(x: string | number) fails both signatures with TS2769: No overload matches this call.
  • An overload set written against any inside the implementation loses the checking that made overloads worth writing; a permissive unknown last signature restores an error path.
  • Arrow functions cannot carry overloads directly; the type of the constant holds the call signatures and the arrow supplies the body.
  • When every signature maps one input type to one output type, a single generic signature with a conditional return type is shorter, distributes over unions, and keeps working after the union grows.

Basic syntax and type signatures

typescript
// Two call signatures, one implementation. function pad(value: string, length: number): string; function pad(value: number, length: number): string; function pad(value: string | number, length: number): string { return String(value).padStart(length, "0"); } pad("7", 3); // string pad(7, 3); // string // pad(true, 3); // TS2769: No overload matches this call

The shape of the construct:

typescript
interface Parser { parse(input: string): Document; parse(input: Uint8Array): Document; parse(input: string, options: Options): Document; } // Ambient overloads: no body at all. declare function query(selector: string): Element | null; declare function query<T extends Element>(selector: string): T | null;

Two rules of the resolution algorithm decide most outcomes. Signatures are tried in declaration order, and the first one that accepts the arguments is chosen. If no signature accepts them, the error is reported against the call (TS2769) with a note for each signature, and the implementation signature is not tried. That last point is what surprises people coming from languages where the implementation is a fallback: adding a signature to the implementation alone does nothing for callers.

Comparison of ways to express one function with several shapes

ApproachCall-site safetyHandles new input types automaticallyWorks for union argumentsCost
Overload signatureseach call checked against one signatureno, a new signature per typenoverbose, order-sensitive
Single generic signaturerelational types keptyesyesharder error messages
Generic with conditional returnfull, if written rightyesyes, distributescomplex types to read
Union parameterfull for the parameteryesyesno per-input return refinement
any catch-all overloadnonen/ayesdefeats the purpose

The decision rule: use overloads when the call shapes genuinely differ (different argument counts, an options object only sometimes present, a callback in a different position). Use a generic signature when the difference is only in types and the return type follows from the input.

Practical edge cases and deep dives

1. Order decides reachability

typescript
function create(tag: "input"): HTMLInputElement; function create(tag: "canvas"): HTMLCanvasElement; function create(tag: string): HTMLElement; function create(tag: string): HTMLElement { return document.createElement(tag); } const i = create("input"); // HTMLInputElement const c = create("canvas"); // HTMLCanvasElement const d = create("div"); // HTMLElement

Reverse the first two lines and "div" would still resolve to the general signature, but "input" would too — the specific signatures after the general one are dead for every argument the general signature accepts. The common variation is a (value: unknown) or (value: any) signature placed first as a convenience catch-all, which swallows every later signature and masks argument errors entirely. Put the general case last, and make it as narrow as the runtime behavior justified: (tag: string) accepts literals and variables, which is usually what is wanted for a DOM factory but wrong for a parser that only handles specific formats.

2. Overloads reject union arguments

typescript
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; } double("a"); // ok double(2); // ok declare const both: string | number; // double(both); // TS2769: No overload matches this call

Each signature is checked as a whole, and neither accepts string | number. Options, in order of preference:

typescript
// 1. A signature that accepts the union. function double2(x: string | number): string | number; // 2. A generic signature that distributes. function double3<T extends string | number>(x: T): T extends string ? string : number; function double3(x: string | number): string | number { /* ... */ } // 3. Map over the union at the call site. function doubleAll(values: (string | number)[]): (string | number)[] { return values.map((v) => double(v as string & number)); // ugly: the cast is the smell }

Option 3 is what people actually write, and the cast is the signal that the overload set does not model the domain. A union parameter is nearly always the correct model when every member is handled by the same body.

3. Overloads on methods, classes, and this

typescript
class Store { private data = new Map<string, unknown>(); get(key: string): unknown; get<T>(key: string, fallback: T): T; get<T>(key: string, fallback?: T): unknown | T { return this.data.has(key) ? this.data.get(key) : fallback; } set(key: string, value: unknown): this { // fluent chaining this.data.set(key, value); return this; } } const store = new Store(); const a = store.get("x"); // unknown const b = store.get("x", 0); // number store.set("a", 1).set("b", 2); // this-typed chaining works

Inside a class body, overload signatures are written as methods without bodies and must be followed immediately by the implementation; splitting them across a getter or a field is a syntax error. For functions that depend on their receiver, this is declared as a fake first parameter and is not counted in the arity:

typescript
function attach(this: HTMLElement, name: string): void; function attach(this: Document, name: string): void; function attach(this: HTMLElement | Document, name: string): void { /* ... */ } declare const el: HTMLElement; attach.call(el, "x"); // checked against the HTMLElement signature

4. An arrow function with overloads is a typed constant

typescript
type Comparator = { (a: number, b: number): number; (a: string, b: string): number; }; const compare: Comparator = (a: number | string, b: number | string): number => { if (typeof a === "number" && typeof b === "number") return a - b; return String(a).localeCompare(String(b)); }; compare(1, 2); compare("a", "b"); // compare(1, "b"); // TS2769

The call signatures live on the object type, the arrow supplies the single body, and the annotation on the parameters is written as a union because the arrow's own signature is checked against the whole type only loosely. Declaring compare twice (const compare = ...; function compare(...)) is a duplicate-identifier error, and a second declare function with the same name in a module merges only when both are ambient.

5. Replacing an overload set with one generic signature

typescript
interface Events { click: MouseEvent; keydown: KeyboardEvent; custom: { detail: string }; } // Overload-per-key grows linearly and still rejects union keys. function on(event: "click", handler: (e: MouseEvent) => void): void; function on(event: "keydown", handler: (e: KeyboardEvent) => void): void; function on(event: string, handler: (e: unknown) => void): void; // One signature, correlated key and payload, distributes over unions. function subscribe<K extends keyof Events>( event: K, handler: (payload: Events[K]) => void, ): () => void { throw new Error("unimplemented"); } subscribe("click", (e) => e.clientX); // e: MouseEvent declare const anyEvent: keyof Events; subscribe(anyEvent, (e) => { /* e: MouseEvent | KeyboardEvent | { detail: string } */ });

The generic form keeps the relationship between the key and the payload inside a single signature, so the union case works and a new event needs no new overload. It loses one thing: when the call is wrong, the error names the generic constraint instead of the closest overload, which is sometimes harder to read. In exchange it scales, and it composes with Parameters and ReturnType where an overload set composes into only the last signature.

Common mistakes and compiler errors

Error or symptomCauseFix
TS2394: This overload signature is not compatible with its implementation signaturea signature accepts shapes the implementation cannotwiden the implementation parameter types or narrow the signature
TS2769: No overload matches this callno signature accepts the argument typesadd a union or generic signature; check literal widening
TS2554: Expected 3 arguments, but got 2the implementation signature is being resolved, not a call signatureadd the missing signature for that arity
A later signature is never usedan earlier, broader signature matches everythingmove specific signatures first
Calling with the implementation's parameter list failsthe implementation signature is not callable from outsidedeclare a public signature for that shape
TS2391: Function implementation is missing or not immediately following the declarationa comment or statement between signatures and bodyplace the body directly after the signatures
Duplicate function implementationtwo implementations for one namekeep one body
TS2559: Type 'X' has no properties in common with type 'Y' on an arrow overloadthe arrow's parameter type does not cover the call signaturesannotate parameters with the union and cast inside
Return type overload ignoredresolution chooses by arguments onlybranch on an argument, or use a conditional return type
Parameters become any inside the bodyimplementation signature typed anytype the implementation with the union and narrow

Two practices keep overload sets honest. First, always give the implementation a parameter list wide enough to be checked but narrow enough to be useful — the union of the signature parameter types, not any — because the body is where the runtime branches and where a mistake is cheapest to catch. Second, add a test or a compile-only assertion for each signature, since removing a signature that nothing calls is invisible: a type-level check such as const _: HTMLCanvasElement = create("canvas") fails to build the moment the signature disappears, which an unexercised overload never does.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.