Sub topic 5
When Not to Use Overloads
Assume you know basic TypeScript types, unions, literal types, typed functions, typeof and Array.isArray narrowing, classes, and interfaces. This chapter focuses on choosing an alternative to overloads when they add complexity without improving the function's type.
Function overloads are useful when a function has several public call shapes and the return type depends on which shape the caller uses. They are not automatically the best choice whenever a function accepts more than one type.
The main alternatives are:
- A union type for unrelated inputs with the same result type.
- Optional or rest parameters for simple argument-count variations.
- A generic for a reusable relationship between input and output.
- A discriminated union when several related values belong together.
Start with the return type
Consider this function:
function lengthOf(value: string | readonly unknown[]): number {
return value.length;
}
const textLength = lengthOf("hello");
const listLength = lengthOf([1, 2, 3]);A union is a good choice because both inputs produce the same result type: number. The caller does not need to know which input branch ran.
Overloads would make the declaration longer without giving callers more useful information:
function lengthOf(value: string): number;
function lengthOf(value: readonly unknown[]): number;
function lengthOf(value: string | readonly unknown[]): number {
return value.length;
}This version is valid, but it does not preserve a meaningful relationship between the input and output. Both overloads promise exactly the same result type.
Use an overload when the call shape changes the return type or the available result. Use a union when the call shape changes only the implementation's internal path.
Use optional parameters for simple absence
A function with one optional value usually needs an optional parameter, not two overloads.
function greet(name?: string): string {
return name === undefined ? "Hello!" : `Hello, ${name}!`;
}
greet();
greet("Ada");The ? means that callers may omit the argument. The return type stays string in both cases.
The overload version is more verbose:
function greet(name: string): string;
function greet(): string;
function greet(name?: string): string {
return name === undefined ? "Hello!" : `Hello, ${name}!`;
}Overloads can still be useful when omitted and supplied arguments produce different return types. For example, a lookup function might return User | undefined without an identifier but User with a validated identifier. If the result does not change, an optional parameter communicates the rule more directly.
Rest parameters are similarly useful when the function accepts any number of values and always returns the same kind of result:
function joinWords(separator: string, ...words: string[]): string {
return words.join(separator);
}
joinWords(", ", "red", "green", "blue");
joinWords(" / ", "home", "docs");Do not create one overload for every supported argument count when a rest parameter describes the API accurately.
Use generics for input-output relationships
A generic is a type parameter that lets one function work with many types while preserving a relationship between them.
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const firstName = first(["Ada", "Lin"]);
const firstNumber = first([10, 20, 30]);TypeScript infers T from the argument:
firstNamehas typestring | undefined.firstNumberhas typenumber | undefined.
You could write separate overloads for strings and numbers:
function firstValue(items: readonly string[]): string | undefined;
function firstValue(items: readonly number[]): number | undefined;
function firstValue(
items: readonly (string | number)[]
): string | number | undefined {
return items[0];
}That approach does not scale. It would require another overload for every supported element type. The generic expresses the general rule once: the result has the same element type as the input array.
A generic is usually preferable when:
- The same relationship applies to many possible types.
- The implementation does not need separate behavior for each type.
- The output can be described in terms of an input type parameter.
A generic does not replace every overload. If the function genuinely behaves differently for unrelated shapes, overloads may communicate that distinction better.
Use one union when the result requires narrowing
A union return type can be more honest when the caller must inspect the result.
type SearchResult =
| { kind: "found"; value: string }
| { kind: "missing" };
function search(cache: Map<string, string>, key: string): SearchResult {
const value = cache.get(key);
return value === undefined
? { kind: "missing" }
: { kind: "found", value };
}
const result = search(new Map([["language", "TypeScript"]]), "language");
if (result.kind === "found") {
console.log(result.value.toUpperCase());
}The kind property is a discriminant. It tells the caller which member of the union it has. A union is preferable here because the function has one consistent result model, and the caller must handle both outcomes.
Do not add overloads merely to hide a real uncertainty in the result. If a lookup can fail, returning string | undefined or a discriminated union makes that possibility visible.
Compare the choices
| Situation | Prefer | Reason |
|---|---|---|
| Several input types produce the same result type | Union | One signature describes the behavior |
| An argument may be omitted and the result stays the same | Optional parameter | The syntax matches the call |
| Any element type follows the same input-output rule | Generic | The relationship scales to new types |
| The return type depends on distinct call shapes | Overloads | Each call gets a precise result type |
| The caller must inspect one of several outcomes | Discriminated union | The result model is explicit |
This decision process avoids two common problems. First, a large overload list can become difficult to maintain. Second, overload order affects resolution. A general overload placed before a specific one can prevent the specific signature from being selected. Generic inference also has special behavior for overloaded functions, including cases where inference uses the last signature. Fewer, clearer signatures reduce these surprises.
A practical rule
Start with the simplest signature that remains precise:
- Try a union if all valid inputs have the same result type.
- Try an optional or rest parameter if the difference is argument presence or count.
- Try a generic if the output preserves a type from the input.
- Use overloads when distinct call shapes need distinct return types or distinct caller-visible guarantees.
Avoid using any just to make one implementation signature accept everything. An implementation can use a union and narrow it safely:
function describe(value: string | number): string {
if (typeof value === "string") {
return `text with ${value.length} characters`;
}
return `number: ${value}`;
}This function has one result type, so an overload would not improve the public API. The union keeps the accepted inputs visible, while narrowing keeps the implementation safe.
Exercise
Should toUpperCase(value: string | string[]): string | string[] use overloads, a union, or a generic if it returns one uppercase string for a string input and an uppercase array for an array input?
Show answer
Use overloads, because the return type depends on the input shape. A string input returns string, while an array input returns string[]. A single union signature would lose that input-output relationship.