Sub topic 5
When Not to Use Overloads
This chapter assumes you can write overload signatures and an implementation signature, and that you know unions, optional parameters, basic generics, and narrowing with typeof. The earlier chapters showed how to write overloads. This one covers when to use something else, because overloads are the heaviest tool TypeScript offers for typing a function that accepts several kinds of input.
What overloads cost
An overload set is several signatures plus an implementation that the compiler checks only loosely. That has four costs:
- Callers cannot pass a union. The compiler resolves a call against each overload separately. An argument of type
string | numbermatches neither(x: string)nor(x: number), so you must add a third overload for the union. - The implementation is barely checked. TypeScript confirms that each overload is compatible with the implementation signature. It does not confirm that the body returns the right type for each overload.
- Error messages get worse. When no overload matches, the message refers to the last overload or lists every candidate, and neither tells the caller what to fix.
- Maintenance multiplies. Adding one new input type means adding one new signature, and the signatures can drift out of order or out of sync with the body.
You accept these costs when overloads are the only way to describe the function. Often they are not.
Ask what actually varies
Before writing a second signature, look at how the call shapes differ from each other. Three differences have simpler tools than overloads.
The sections below take each branch in turn.
Use a union when the return type does not change
If every call shape returns the same type, overloads add nothing. A union parameter describes the function in one line and accepts union arguments, which overloads reject.
// Overloaded version: three signatures for one idea.
function lengthOverloaded(x: string): number;
function lengthOverloaded(x: unknown[]): number;
function lengthOverloaded(x: string | unknown[]): number {
return x.length;
}
// Union version: one signature.
function lengthUnion(x: string | unknown[]): number {
return x.length;
}
const input: string | unknown[] = Math.random() > 0.5 ? "abc" : [1, 2, 3];
// lengthOverloaded(input); // Error: No overload matches this call.
console.log(lengthUnion(input)); // OKThe overloaded version rejects input even though both of its overloads return number and the body handles both cases. The caller holds a perfectly valid value, and the overloads block it.
The fix with overloads is to add a third signature lengthOverloaded(x: string | unknown[]): number. Once you have written that signature, the first two are redundant.
Use optional or default parameters when trailing arguments are missing
A common mistake is writing one overload per argument count.
function greetOverloaded(name: string): string;
function greetOverloaded(name: string, greeting: string): string;
function greetOverloaded(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
// One signature does the same job:
function greet(name: string, greeting = "Hello"): string {
return `${greeting}, ${name}!`;
}
const custom: string | undefined = Math.random() > 0.5 ? "Hi" : undefined;
console.log(greet("Ada"));
console.log(greet("Ada", "Welcome"));
console.log(greet("Ada", custom)); // OK: undefined falls back to the default
// greetOverloaded("Ada", custom); // Error: undefined is not assignable to stringThe default-parameter version is shorter. It also handles a caller who forwards a possibly undefined value, which the overloaded version rejects because its second signature requires a string.
Use this replacement only when the shapes differ by trailing arguments of the same kind and the result type does not depend on them. Two situations call for overloads instead:
- The omitted arguments change the return type. For example, a function that returns a
stringwithout a callback and aPromise<string>with one. - Optional parameters would permit combinations you want to forbid. The
createDateexample from earlier in this tutorial takes either one number or exactly three. Making the second and third parameters optional would letcreateDate(2026, 11)compile. Overloads reject that call, so they are the right tool there.
Use a generic when the return type mirrors the argument type
The first overload example in this tutorial, toArray, listed one signature per input type. When the output type is a simple function of the input type, a generic type parameter says the same thing once.
function wrapOverloaded(value: string): { value: string };
function wrapOverloaded(value: number): { value: number };
function wrapOverloaded(value: boolean): { value: boolean };
function wrapOverloaded(value: unknown): { value: unknown } {
return { value };
}
// Same behaviour, and it works for every type, not only three.
function wrap<T>(value: T): { value: T } {
return { value };
}
function toArray<T>(value: T): T[] {
return [value];
}
const w = wrap("x"); // { value: string }
const a = toArray(1); // number[]
const b = toArray(true); // boolean[]
const c = toArray<string | number>(Math.random() > 0.5 ? "x" : 1); // (string | number)[]The generic version has three advantages:
- It works for types you did not list.
- It accepts union arguments, where each overload matched a single type.
- The body is checked against
T, so returning something unrelated tovalueis an error. The overloaded implementation returned{ value: unknown }and the compiler could not tell whether it matched each signature.
If you want to restrict the accepted types, add a constraint:
function toArrayRestricted<T extends string | number>(value: T): T[] {
return [value];
}
const lit = toArrayRestricted("x"); // "x"[] (the literal type is kept)
const wide = toArrayRestricted(Math.random() > 0.5 ? "x" : 1); // (string | number)[]Conditional return types for a computed mapping
Sometimes the return type is not the argument type itself but a function of it. A function that turns a string into a number, or an array of strings into an array of numbers, is an example. You can express the mapping with a conditional type instead of two overloads.
type Parsed<T extends string | string[]> = T extends string ? number : number[];
function parse<T extends string | string[]>(input: T): Parsed<T> {
const value: string | string[] = input;
const result = typeof value === "string" ? Number(value) : value.map(Number);
return result as Parsed<T>;
}
const n = parse("42"); // number
const ns = parse(["1", "2"]); // number[]
const mixed: string | string[] = Math.random() > 0.5 ? "7" : ["7", "8"];
const m = parse(mixed); // number | number[]Compare this with an overloaded parse. The overloaded version rejects mixed unless you add a third overload. The conditional version distributes over the union and returns number | number[] with no extra signature.
The price is the cast. TypeScript cannot check that a runtime number satisfies a deferred Parsed<T>, so you assert it with as. That is the same unchecked-body problem overloads have, only moved to a different line. Choose the conditional form when callers will pass union values or when the mapping would need many overloads. Choose overloads when the mapping is small and the readable signatures matter more than union support.
Use one callback signature when only the callback arity differs
A callback that takes fewer parameters is assignable to a callback type that takes more. A function declared as (item: number) => void can be passed where (item: number, index: number) => void is expected. So there is no reason to overload on callback arity.
// Unnecessary: three overloads that differ only in callback arity.
function eachOverloaded(items: number[], callback: () => void): void;
function eachOverloaded(items: number[], callback: (item: number) => void): void;
function eachOverloaded(items: number[], callback: (item: number, index: number) => void): void;
function eachOverloaded(items: number[], callback: (item: number, index: number) => void): void {
items.forEach((item, index) => callback(item, index));
}
// Enough: declare the callback with the most parameters you will pass.
function each(items: number[], callback: (item: number, index: number) => void): void {
items.forEach((item, index) => callback(item, index));
}
each([10, 20], () => console.log("tick"));
each([10, 20], (item) => console.log(item));
each([10, 20], (item, index) => console.log(index, item));Callers that supply a shorter callback type-check against the single signature. The one exception is when the callback's arity changes the return type, because then the signatures genuinely differ.
Another way to see the rule
An overload is justified when the compiler needs to know a relationship between the arguments and the result that no single signature can express. Each tool covers a narrower case:
| What varies between calls | Best tool | Why |
|---|---|---|
| Parameter type, same return type | Union parameter | One signature, accepts union arguments |
| Trailing arguments present or absent, same return type | Optional or default parameter | One signature, tolerates `undefined` |
| Return type mirrors the argument type | Generic | Works for any type, checked body |
| Return type is a type-level function of the argument | Generic with conditional type | Handles unions, needs a cast |
| Callback arity | One signature with the fullest callback | Fewer-parameter callbacks are assignable |
| Different argument counts with different meanings | Overloads | Forbids invalid combinations |
| Unrelated argument-to-return pairs | Overloads | No single type expresses the pairing |
The last two rows are where overloads win. createDate(timestamp) and createDate(year, month, day) take different counts of arguments and mean different things. A function like the following has no relationship between its input and output types except the one you list:
function read(source: string): string;
function read(source: number): Uint8Array;
function read(source: string | number): string | Uint8Array {
return typeof source === "string" ? `file:${source}` : new Uint8Array(source);
}
const text = read("notes.txt"); // string
const bytes = read(4); // Uint8ArrayHere a string argument produces a string and a number argument produces a Uint8Array. A generic cannot express that without a conditional type, and a union would lose the pairing. Two short overloads read more clearly than the conditional alternative, so this is a good use of overloads.
A refactoring checklist
Run through these questions when you review an overload set:
- Do all overloads return the same type? If so, replace them with a union or optional parameters.
- Is each return type just the argument type, or a container of it? If so, replace them with a generic.
- Do the signatures differ only by trailing parameters? If so, make those parameters optional, unless the missing arguments change the return type or must be forbidden.
- Do the signatures differ only by callback arity? If so, keep the callback with the most parameters.
- Would callers reasonably pass a union value? If so, prefer a form that accepts unions, or add an overload for the union.
- Is the remaining set small, and does each signature say something the others cannot? If so, keep the overloads.
Mistakes people make when replacing overloads
- Replacing overloads with a union when return types differ. A signature
(x: string | number): string | numberforces every caller to narrow the result. Use a generic or keep the overloads. - Making a type parameter that appears only once. In
function f<T>(x: T): void,Tdoes not connect anything and can be written as the constraint itself, such asx: string. A generic helps only when the type links two or more places, such as a parameter and the return type. - Forgetting that the cast is unchecked. Conditional return types and overloads both rely on you getting the body right. Test both runtime branches.
- Using optional parameters where the combination matters. If a second argument is only valid together with a third, optional parameters cannot express that. Overloads can.
Exercises
Exercise
A function size(x: string | Map<string, unknown>): number was written as two overloads, one for string and one for Map<string, unknown>, both returning number. A caller with a string | Map<string, unknown> value gets "No overload matches this call". What is the simplest fix, and why does it work?
Show answer
Delete the overloads and keep one signature, function size(x: string | Map<string, unknown>): number. Every call shape returns the same type, so overloads add nothing. With a union parameter, a union argument matches the single signature, whereas overload resolution tries each overload separately and a union value matches neither one.
Exercise
Rewrite these three signatures as a single declaration, then say whether the rewrite is better than the original: function identity(x: string): string; function identity(x: number): number; function identity(x: boolean): boolean; (plus an implementation signature identity(x: unknown): unknown).
Show answer
Use a generic: function identity<T>(x: T): T { return x; }. The return type mirrors the argument type, so one type parameter replaces all three overloads. It is better because it works for every type, accepts union arguments, and the body is checked (returning anything other than x, or a value not typed T, is an error), whereas the overloaded implementation returning unknown was not checked against each signature.
Exercise
A function open(path: string): Handle and open(path: string, mode: "r" | "w"): Handle exists as two overloads. Should it use an optional parameter instead? What about fetchData(url: string): string and fetchData(url: string, onDone: (data: string) => void): void?
Show answer
Yes for open: the signatures differ only by a trailing argument and return the same type, so open(path: string, mode?: "r" | "w"): Handle (or a default value) is simpler and also accepts a possibly undefined mode. No for fetchData: supplying the callback changes the return type from string to void, which one signature with an optional parameter cannot express, so keep the overloads.