Sub topic 1
The Problem: One Function, Several Call Shapes
Prerequisites
This chapter assumes that you know basic TypeScript types, including unions and literal types. You should be comfortable writing and calling typed functions, narrowing values with typeof and Array.isArray, and reading simple classes and interfaces.
One Function Can Have Several Valid Call Shapes
A function's call shape is the combination of its accepted arguments and the value it returns. Many functions support more than one call shape.
For example, a function that reads a configuration value might accept either a key or a list of keys:
- With one key, it returns one value.
- With several keys, it returns several values.
The JavaScript implementation can handle both cases:
function getValues(input: string | string[]) {
if (Array.isArray(input)) {
return input.map((key) => `value for ${key}`);
}
return `value for ${input}`;
}
const one = getValues("theme");
const many = getValues(["theme", "language"]);At runtime, this code behaves correctly. However, TypeScript may infer the return type as string | string[] for both calls. That type is safe, but it does not describe what the function actually does for each argument.
const one = getValues("theme");
// Type: string | string[]
const many = getValues(["theme", "language"]);
// Type: string | string[]The caller knows that one should be a string, but TypeScript does not preserve that relationship. The caller must narrow the result before using it as a string.
if (typeof one === "string") {
console.log(one.toUpperCase());
}This extra check is useful when the input is genuinely unknown. It is inconvenient when the caller already supplied a value whose type determines the result.
The Limitation of One Union Signature
A union type says that a value can be one of several types. In the example above, string | string[] means that input can be either a string or an array of strings.
A union is often the right choice when the return type is the same for every input. For example, this function always returns a number:
function count(value: string | string[]): number {
return Array.isArray(value) ? value.length : value.length;
}
const countOne = count("theme"); // number
const countMany = count(["theme", "language"]); // numberThe parameter varies, but the result does not. A single union-typed signature describes this function clearly.
The problem changes when the return type depends on the argument type. A broad union return type loses this dependency:
| Argument | Actual result | Union signature exposes | Column |
|---|---|---|---|
| `string` | `string` | `string \ | string[]` |
| `string[]` | `string[]` | `string \ | string[]` |
The function is safe, but its public type is less precise than its behavior. This can spread uncertainty through the rest of a program. Every caller must narrow a result that could have been precise from the beginning.
Overloads Describe the Public Choices
A function overload is a public function signature that describes one valid way to call a function. You can write several overload signatures for one implementation.
The getValues function can describe its two call shapes like this:
function getValues(input: string): string;
function getValues(input: string[]): string[];
function getValues(input: string | string[]): string | string[] {
if (Array.isArray(input)) {
return input.map((key) => `value for ${key}`);
}
return `value for ${input}`;
}
const one = getValues("theme");
// Type: string
const many = getValues(["theme", "language"]);
// Type: string[]The first two signatures are overload signatures. They are the signatures that callers can use. Each one connects a parameter type to its corresponding return type.
The final signature is the implementation signature. It contains the function body and must be able to handle every case described by the overloads.
This gives callers precise types without requiring them to understand the internal branching:
console.log(one.toUpperCase());
for (const value of many) {
console.log(value.toUpperCase());
}The compiler knows that one is a string and many is an array of strings because it selects the overload that matches each call.
A Guided Example: Finding by Key or Predicate
Consider a collection that can find an item in two ways:
- A number selects an item by its position.
- A predicate function selects the first item that satisfies a condition.
A single union signature can express the parameters, but it cannot give each call its most useful result type or document the two choices as clearly:
function findItem(
items: readonly string[],
query: number | ((item: string) => boolean)
): string | undefined {
if (typeof query === "number") {
return items[query];
}
return items.find(query);
}Here, both call shapes happen to return string | undefined, so overloads do not improve the return type. However, overloads can still make the API's supported forms clearer:
function findItem(
items: readonly string[],
index: number
): string | undefined;
function findItem(
items: readonly string[],
predicate: (item: string) => boolean
): string | undefined;
function findItem(
items: readonly string[],
query: number | ((item: string) => boolean)
): string | undefined {
if (typeof query === "number") {
return items[query];
}
return items.find(query);
}
const byIndex = findItem(["a", "b", "c"], 1);
const byPredicate = findItem(["a", "b", "c"], (item) => item === "c");In this example, a union may be simpler because the return type does not vary. Later, you will compare unions, generics, optional parameters, and overloads more systematically.
Visualizing the Relationship
The key idea is not that overloads create separate runtime functions. JavaScript still runs one function body. Overloads create several compile-time views of that body for callers.
When This Problem Calls for Overloads
Overloads are a good fit when all of these statements are true:
- One runtime function supports multiple argument patterns.
- The patterns are intentional parts of the public API.
- The return type, accepted arguments, or both depend on which pattern the caller uses.
- A union return type would force callers to perform unnecessary narrowing.
Overloads are usually unnecessary when a function always returns the same type. They can also be unnecessary when a generic type can preserve the relationship more simply.
For example, a function that returns the first element of any array is naturally generic:
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const firstName = first(["Ada", "Lin"]);
const firstNumber = first([10, 20]);The generic type parameter T represents the element type and keeps it connected to the result. No separate call shapes are needed.
The next step is learning the exact syntax for overload signatures and the implementation that supports them.
Exercise
Why might getValues("theme") have a less useful type when declared with one signature using string | string[] for both its parameter and return value?
Show answer
The return type becomes string | string[], even though a string argument always produces a string. The caller must narrow the result manually. Overload signatures can preserve the relationship between the argument type and the precise return type.