Sub topic 2
Writing Overload Signatures
What this chapter assumes
You should be comfortable with unions, literal types, typed functions, and narrowing with typeof and Array.isArray. You should also know the basics of classes and interfaces. This chapter covers the syntax and rules for writing the list of overload signatures. Later chapters cover the implementation signature in more depth, the order in which the compiler tries signatures, alternatives to overloads, methods, type-level declarations, and pitfalls. This chapter mentions those topics only where you need them to write a working overload.
By the end you should be able to write a complete overloaded function, vary its parameter count and return type per signature, and read the common errors the compiler reports when the list is wrong.
Why you write more than one signature
An ordinary function has one signature: one list of parameters and one return type. An overloaded function has several signatures. Each describes one way to call it. TypeScript uses them to check calls and to pick the return type for each call.
Overloads help when the return type depends on which arguments the caller passes. A single signature with union parameters would give every caller the same wide return type, such as (string | number)[]. Several signatures let a call with a string produce string[] and a call with a number produce number[].
Anatomy of an overloaded function
An overloaded function has two parts, written one after the other with the same name:
- One or more overload signatures. Each is a function header ending in a semicolon, with no body.
- Exactly one implementation, which has a body.
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 first two lines are overload signatures. The third is the implementation signature plus its body. Callers see only the first two. The implementation signature is visible only inside the declaration, where it is used to check the body. The next chapter treats it in full. For now, remember two rules:
- The implementation must be able to handle every call that any overload allows.
- Callers cannot call the implementation signature directly.
Rules for the signature list
The compiler enforces a few structural rules. Most of the errors you see when you first write overloads come from breaking one of them.
Keep the declarations adjacent
All overload signatures and the implementation must be consecutive. You cannot put other statements between them. If anything separates an overload from the next declaration of the same name, TypeScript reports that the function implementation is missing or not immediately following the declaration (error 2391).
function size(x: string): number;
function size(x: unknown[]): number;
function size(x: string | unknown[]): number {
return x.length;
}Comments between the declarations are fine. Code is not.
Do not forget the implementation
A list of overload signatures with no implementation is an error in a .ts file. The only exceptions are ambient declarations (declare function) and .d.ts files, where no implementation exists. The last chapter group covers those. In ordinary code, the final declaration in the group must have a body.
Use the same modifiers on every signature
If you export one signature, export all of them. The same goes for declare and default. TypeScript reports mismatches such as "Overload signatures must all be exported or non-exported" (error 2383).
export function clamp(value: number): number;
export function clamp(value: number, max: number): number;
export function clamp(value: number, max?: number): number {
return max === undefined ? value : Math.min(value, max);
}You write export on the implementation too. The implementation signature itself is not part of the exported type, but the declaration as a whole is.
Give each signature its own types
Each overload is a full signature. It can have its own parameter list, optional and rest parameters, return type, and even its own type parameters. Parameter names can differ between overloads, since only position and type matter to callers. Use names that read well for that particular call shape.
Varying the number of arguments
The most direct use of overloads is to allow certain argument counts and no others. Here is a date helper that takes either a timestamp or a year, month, and day:
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);
createDate(2026, 11, 25);
// createDate(2026, 11); // Error: no overload takes exactly two argumentsThe implementation makes b and c optional so that it can be called with one argument. The overloads do not expose that. A caller cannot pass exactly two arguments, even though the body could technically handle it.
This is the main reason to prefer overloads over a single signature with optional parameters. A signature such as (a: number, b?: number, c?: number) would allow createDate(2026, 11), which is a call you probably do not want to support. Overloads let you list only the argument counts that make sense.
The compiler reports this kind of failure in one of two ways. If no overload takes that many arguments, it says that no overload expects that count and lists the counts that exist. If some overload takes that count but the types do not fit, it reports "No overload matches this call" (error 2769) and shows why each candidate failed.
Optional parameters inside an overload
An individual overload may still contain optional parameters. This is useful when two call shapes share a return type and differ only by a trailing option:
function pad(text: string, width: number): string;
function pad(text: string, width: number, fill: string): string;
function pad(text: string, width: number, fill?: string): string {
return text.padStart(width, fill ?? " ");
}You could write this as one signature, pad(text: string, width: number, fill?: string): string. The two behave the same for callers. When the return type does not change, the single signature is shorter, easier to read, and just as precise. The "When not to use overloads" chapter returns to this decision. Write separate overloads only when the signatures differ in a way an optional parameter cannot express.
Varying the return type by argument
Return types are where overloads earn their keep. Each signature can return something different, and the compiler picks the one that matches the call.
Different parameter types, different results
The toArray example above does this: a string argument gives string[] and a number argument gives number[]. Each signature pairs one input type with one output type, which no single non-generic signature can express.
Literal types as selectors
A common pattern uses string literal types as a key that selects the result. The caller passes a known name and gets back the type that belongs to that name:
const settings: Record<string, number | string> = {
port: 8080,
host: "localhost",
};
function getSetting(name: "port"): number;
function getSetting(name: "host"): string;
function getSetting(name: string): number | string | undefined;
function getSetting(name: string): number | string | undefined {
return settings[name];
}
const port = getSetting("port"); // number
const host = getSetting("host"); // string
const other = getSetting("timeout"); // number | string | undefinedThe third signature is a fallback for any other string. It returns the wide union because the compiler cannot know which setting a general string names. The fallback is deliberately the last one. A call with the literal "port" matches the first signature and never reaches it. Why the order matters is the subject of the next chapters.
In many codebases, a mapping type with a generic lookup would replace this pattern. For a handful of keys with unrelated behavior, literal overloads stay readable.
Signatures with their own type parameters
An overload may declare type parameters that the other overloads do not have:
function firstOr<T>(items: readonly T[]): T | undefined;
function firstOr<T, D>(items: readonly T[], fallback: D): T | D;
function firstOr<T, D>(items: readonly T[], fallback?: D): T | D | undefined {
return items.length > 0 ? items[0] : fallback;
}
const n = firstOr([1, 2, 3]); // number | undefined
const s = firstOr<number, string>([], "none"); // number | stringWith one argument, the result may be undefined. With a fallback, the caller gets the element type or the fallback's type, and undefined is no longer in the result. The two signatures have different type parameters because they have different jobs. Type parameters are inferred per overload, so each signature starts from a clean slate.
Rest parameters and arrays
Overloads can also accept the same data in different shapes. This function takes either separate numbers or an array of them:
function sum(...values: number[]): number;
function sum(values: number[]): number;
function sum(...args: (number | number[])[]): number {
let total = 0;
for (const arg of args) {
if (typeof arg === "number") {
total += arg;
} else {
for (const n of arg) {
total += n;
}
}
}
return total;
}
sum(1, 2, 3); // 6
sum([1, 2, 3]); // 6The implementation uses a rest parameter whose element type is a union. It narrows each element with typeof and handles both shapes. The return type is number for both overloads, so a plain union would be a fair alternative here. The point of the example is that the implementation signature can be written in a quite different form from the overloads, as long as it covers them.
How the signatures relate to the implementation
The compiler checks that each overload signature is compatible with the implementation signature. Compatibility here is loose. It does not require an exact match. Roughly, the implementation's parameters must accept what each overload accepts, and the return types must overlap in a sensible way. In practice, three habits will keep you out of trouble:
- Write the implementation's parameter types as the union of every overload's parameter types.
- Write its return type as the union of every overload's return type.
- Make any parameter that appears in only some overloads optional.
When an overload has no compatible counterpart in the implementation, the compiler reports "This overload signature is not compatible with its implementation signature" (error 2394). Here is one example:
function double(x: number): number;
// Error 2394: this overload is not compatible with the implementation.
function double(x: string): string;
function double(x: number): number {
return x * 2;
}The second overload promises that a string is accepted, but the implementation takes only a number. The compiler reports the error on the incompatible overload. The fix is to widen the implementation (x: number | string) and handle the string case in the body.
Documenting overloads
Each overload signature can have its own doc comment. Editors show the comment for the overload that matches the call you are typing, and they list all overloads in the signature help popup. This is where overloads help callers most, because each call shape can carry its own explanation.
/** Creates a date from a Unix timestamp in milliseconds. */
function makeDate(timestamp: number): Date;
/** Creates a date from a year, a 1-based month, and a day. */
function makeDate(year: number, month: number, day: number): Date;
function makeDate(a: number, b?: number, c?: number): Date {
return b === undefined || c === undefined ? new Date(a) : new Date(a, b - 1, c);
}Place the comment directly above the signature it describes. A comment on the implementation is not shown to callers.
Quick reference
| Question | Answer |
|---|---|
| How many signatures can I write? | As many as you need, plus exactly one implementation. |
| Can overloads have bodies? | No. Only the implementation has a body. |
| Can callers call the implementation signature? | No. Only the overload signatures are visible. |
| Do overloads need the same parameter names? | No. Position and type matter, names do not. |
| Do overloads need the same modifiers? | Yes. Export, `declare`, and `default` must agree. |
| Can overloads have different type parameters? | Yes. Each signature has its own. |
| Must the declarations be adjacent? | Yes. No other code may separate them. |
Common errors when writing signatures
| Symptom | Likely cause | Fix |
|---|---|---|
| "Function implementation is missing or not immediately following the declaration" | A signature group has no body, or code sits between declarations. | Add the implementation directly after the last overload. |
| "This overload signature is not compatible with its implementation signature" | The implementation does not accept one overload's parameters or return type. | Widen the implementation to the union of all overloads. |
| "No overload matches this call" | The argument types fit none of the listed signatures. | Add an overload for that shape, or fix the call. |
| "Overload signatures must all be exported or non-exported" | Modifiers differ between signatures. | Apply the same `export` to every signature and the implementation. |
| A call you wanted to allow is rejected | The implementation allows it, but no overload lists it. | Add a signature. Callers cannot use the implementation's looser shape. |
A worked example, step by step
Suppose you are writing parse. Given a string it returns a number. Given an array of strings it returns an array of numbers. Work through it in four steps.
- List the call shapes you want to support:
stringtonumber, andstring[]tonumber[]. - Write one signature for each shape, with the most specific input type first.
- Write the implementation signature with the union of the inputs and the union of the outputs.
- In the body, narrow with
Array.isArrayand handle each case.
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
if (Array.isArray(input)) {
return input.map((item) => Number(item));
}
return Number(input);
}
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]Check the result by hovering over one and many in your editor, or by assigning each to a variable with an explicit type. If one shows number | number[], the overloads are not being used. That usually means the signatures and implementation are not adjacent, or the function is being called through a different, wider declaration.
Summary
- An overloaded function is a group of bodiless signatures followed by one implementation, all adjacent and sharing modifiers.
- Each signature has its own parameters, return type, and type parameters.
- Overloads let you allow only specific argument counts and tie each input shape to its own return type.
- The implementation signature must be wide enough to cover every overload, and callers never see it.
- The compiler does not check that the body returns what each overload promises.
Exercise
Write overloads for a function repeat that takes a string and a count and returns a string, or takes an array of strings and a count and returns a string array. Each result repeats the input count times. Include a compatible implementation.
Show answer
One solution: function repeat(input: string, count: number): string; function repeat(input: string[], count: number): string[]; function repeat(input: string | string[], count: number): string | string[] { if (Array.isArray(input)) { const result: string[] = []; for (let i = 0; i < count; i++) { result.push(...input); } return result; } return input.repeat(count); } The two overloads are adjacent and bodiless. The implementation takes the union of the inputs and returns the union of the outputs. It narrows with Array.isArray to handle each shape. A call such as repeat("ab", 2) has type string, and repeat(["a"], 2) has type string[].
Exercise
The following code fails to compile. Name the error and fix it without removing either overload. function toLabel(x: number): string; function toLabel(x: boolean): string; function toLabel(x: number): string { return String(x); }
Show answer
The second overload is not compatible with the implementation, because the implementation accepts only a number (error 2394, "This overload signature is not compatible with its implementation signature"). Widen the implementation parameter to the union of the overloads: function toLabel(x: number | boolean): string { return String(x); }. Both overloads then match the implementation, and callers can still pass a number or a boolean.
Exercise
Why would createDate(2026, 11) be rejected when createDate's implementation has optional parameters b and c?
Show answer
Callers only see the overload signatures. The two overloads take either one argument or three, so a call with two arguments matches neither. The implementation's optional parameters are internal and are not visible to callers.