Sub topic 1
The problem: one function, several call shapes
JavaScript functions often accept different kinds of arguments and behave differently for each. A function might take a string or an array of strings, or a timestamp or a year, month and day. The runtime handles this with an if. TypeScript has to describe it in a type, and a single signature often can't do that precisely.
This chapter shows where that limit appears and what each workaround costs. It also introduces the feature that fixes the problem, function overloads. Later chapters cover the syntax and rules in detail.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript types, including union types (
string | number) and literal types ("id"). - How to write and call typed functions, including optional parameters.
- How to narrow a type with
typeofandArray.isArray. - Classes and interfaces at a basic level. They matter in later chapters, not here.
The examples compile with strict mode on. You can paste them into the TypeScript Playground or a local project.
Call shapes in JavaScript
A call shape is the combination of argument count and argument types that a call uses. JavaScript puts no limit on how many call shapes one function accepts. The built-in Array.prototype.slice can be called with no arguments, a start index, or a start and end. new Date() accepts nothing, a timestamp, a string, or several numeric parts.
Library authors write functions like this because callers find them convenient. One name covers a family of related operations, and the function decides what to do from the arguments it receives.
A typical hand-written example looks like this:
function parseValue(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}The behavior is simple. A string becomes a number, and an array of strings becomes an array of numbers. A person reading the code sees two cases. The type above describes something weaker.
What a union signature loses
The signature (input: string | string[]): number | number[] makes two independent statements. The input can be either kind. The output can be either kind. It says nothing about how the two are connected. Whoever passes a string gets back number | number[], the same type as someone who passes an array.
function parseValue(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const one = parseValue("42");
// The call site knows it passed a string, but the type is number | number[].
const next = one + 1;
// Error: Operator '+' cannot be applied to types 'number | number[]' and 'number'.
const many = parseValue(["1", "2"]);
many.map((n) => n * 2);
// Error: Property 'map' does not exist on type 'number'.The code at each call site is correct. The compiler rejects it because the type has forgotten a fact the caller knows: the argument was a string, so the result is a number.
Callers are then forced to repeat that knowledge as a runtime check or a type assertion:
const one = parseValue("42");
if (typeof one === "number") {
console.log(one + 1);
}
const many = parseValue(["1", "2"]) as number[];
console.log(many.map((n) => n * 2));The typeof check is wasted work, and the as number[] assertion is unchecked. If someone later changes the argument to a string, the assertion stays in place and the program crashes at runtime.
The core of the problem
A union signature models each parameter and the return value separately. Many functions need a relationship between them: this kind of input produces that kind of output. A plain signature can't express a relationship between parameters and the return type.
The same gap exists between parameters. Consider a function that accepts either a timestamp or a year, month and day.
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); // intended
createDate(2026, 11, 25); // intended
createDate(2026, 11); // compiles, but it is neither intended shapeThe optional parameters allow the third call. At runtime the function sees b defined and c undefined, takes the first branch, and silently returns a date built from the timestamp 2026. No error appears at compile time or at runtime. The type allows more call shapes than the function supports.
Tempting workarounds and their costs
Before using overloads, check what else you could do. Each option is reasonable in some situation, and each has a specific cost here.
Return `any`
function parseValueLoose(input: string | string[]): any {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const x = parseValueLoose("42");
x.toFixed(2); // works
x.nope(); // compiles, then throws "x.nope is not a function" at runtimeThe any type turns off checking for every caller. It removes the annoying errors along with the useful ones, and the misuse shows up only when the program runs.
Assert at every call site
Callers can write as number or as number[]. This moves the burden to every caller, and the compiler cannot check any of those assertions.
Write separate functions
You could publish parseOne and parseMany instead. This is often the best design when you control the API, because each function has one clear signature. It is not always possible. The function may already exist, the API may be fixed by a library or by existing callers, or you may be typing a function that mirrors a JavaScript API.
Use a generic with a conditional type
A generic function with a conditional return type, for example T extends string ? number : number[], can express the relationship. It works, but it has costs. The implementation body usually needs an assertion, because TypeScript cannot check a branch of a body against a deferred conditional type. The signature is harder to read, and error messages become more confusing. Conditional types suit a relationship defined by a rule over many types. They are heavy for two or three fixed call shapes.
Use a discriminated parameter
If the real difference is a mode, you can ask callers to pass an options object with a discriminant property. This is a good design, covered later under alternatives, but it changes the call shapes. It does not describe the ones that already exist.
The table summarizes these options for the parseValue problem.
| Approach | Precise result for each input | Safe for callers | Cost |
|---|---|---|---|
| Union signature | No | Yes, but callers must narrow | Callers repeat checks |
| Return `any` | No | No | Errors appear at runtime |
| Assertion at call site | Only by trust | No | Every caller repeats it |
| Separate functions | Yes | Yes | Changes the API |
| Generic with conditional type | Yes | Mostly | Harder to read, body needs casts |
| Overloads | Yes | Yes | Extra signatures to maintain |
The idea behind overloads
An overloaded function has several declared call shapes. Each one is its own signature with its own parameters and return type. The compiler checks a call against these signatures and uses the matching one. There is still one function at runtime.
Here is parseValue with two overload signatures. Read it as a preview. The next chapter explains each part.
function parseValue(input: string): number;
function parseValue(input: string[]): number[];
function parseValue(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const one = parseValue("42"); // number
const many = parseValue(["1", "2"]); // number[]
console.log(one + 1); // 43
console.log(many.map((n) => n * 2)); // [ 2, 4 ]Both call sites now get the precise result type, and neither needs a check or an assertion. The body is unchanged. Only the declared signatures changed.
The first two lines are the overload signatures. They carry no body, and they are the only signatures callers can see. The third is the implementation signature. It has a body and is wide enough to handle every overload. Callers cannot call it directly. That rule has consequences, and chapter three covers them.
Overloads also fix the argument-count problem
For createDate, overloads declare the two valid shapes and nothing else:
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 still uses optional parameters, because one body has to cover both shapes. Callers see only the two precise shapes, so the two-argument call is now a compile-time error.
Overloads exist only at compile time
TypeScript erases types when it compiles to JavaScript. The overload signatures disappear, and only the implementation remains. This is the compiled output of the parseValue example:
function parseValue(input) {
return Array.isArray(input) ? input.map(Number) : Number(input);
}Languages such as Java or C# have overloading too, but there the runtime picks one of several separate method bodies. TypeScript has a single body that you write to handle every case, usually by narrowing the parameter with typeof, Array.isArray or a check for undefined.
Two consequences follow from this.
- The compiler does not verify that the body does what the overload signatures claim. It checks only that each overload signature is compatible with the implementation signature. This is a source of real bugs, discussed in the pitfalls chapter.
- You can't overload by adding another function with the same name in a different scope or file. Overload signatures must sit together, directly before one implementation.
Recognizing when you have this problem
Not every function with a union parameter needs overloads. A function needs them when the relationship between parameters and result matters to callers. These signs usually indicate the problem:
- The return type changes depending on which type, or which literal value, was passed. For example,
"text"returns a string and"bytes"returns a byte array. - The number of arguments determines the meaning, and some counts are invalid.
createDate(2026, 11)is the example. - Callers keep writing
typeofchecks orasassertions on a return value they could have predicted. - Some parameters are required only when another parameter has a particular type.
- You are writing a type for an existing JavaScript API that already behaves this way.
Now compare with a function that only appears to have the problem:
function length(x: string | unknown[]): number {
return x.length;
}This function accepts two kinds of input, but the result is always a number. The input type has no effect on the output type, so the union signature loses nothing. Overloads would only add noise. Chapter five treats this decision in detail. For now, the test to apply is this: does a caller learn something about the result from knowing which argument type they passed? If yes, you probably have the overload problem. If no, keep the union.
A short worked decision
Suppose a teammate asks you to type this function.
function normalize(input: string | string[]): string | string[] {
return Array.isArray(input) ? input.map((s) => s.trim()) : input.trim();
}Walk through the questions in order.
- Does the output type depend on the input type? Yes. A string produces a string, and an array produces an array.
- Do callers know the input type at the call site? Almost always. They pass a literal or a variable with a known type.
- Is a generic simpler? A generic
<T extends string | string[]>(input: T): Twould claim that the result has the same type as the input, including for a subtype ofstring. That claim is false here, becausetrimreturns a plainstring. Even in this simple case, the generic would be less accurate than two overloads. - Can you split into two functions? Perhaps, but it changes the API.
Two overloads (string to string, string[] to string[]) are the accurate and readable choice. The same walk-through on length ends at question 1, with an answer of no, and a union is enough.
What comes next
The rest of this tutorial works from this problem statement:
- Writing overload signatures and the implementation signature that must be compatible with them.
- How the compiler selects an overload and why order matters.
- When a union, an optional parameter or a generic is the better description.
- Overloads on class methods, in interfaces and in
.d.tsdeclarations. - Common pitfalls, such as bodies the compiler does not check and surprises with inference.
Each later chapter builds on the single idea established here: one runtime function, several declared call shapes, each with its own precise result.
Exercises
Exercise
A function is declared as function wrap(x: string | number): string[] | number[]. A caller writes const r = wrap("a"); r[0].toUpperCase();. Why does this fail to compile, and what information does the signature fail to express?
Show answer
The type of r is string[] | number[], so r[0] is string | number, and toUpperCase does not exist on number. The signature states the input type and the output type independently. It does not say that a string input produces a string[] and a number input produces a number[]. Two overloads, wrap(x: string): string[] and wrap(x: number): number[], would express that relationship.
Exercise
For each function, say whether the overload problem applies (the result or valid argument combinations depend on the argument shape) or a plain union is enough.
1. function isEmpty(x: string | unknown[]): boolean
2. function open(target: string): Handle and function open(target: number, mode: "r" | "w"): Handle implemented together, where open(5) must be rejected.
3. function load(kind: "text" | "binary"): string | Uint8Array, where callers always pass a literal and need the matching result type.
Show answer
1. A union is enough, because the result is always boolean. 2. The overload problem applies, because mode is required only when the target is a number. With optional parameters, open(5) would compile, and overloads reject it. 3. The overload problem applies, because the literal argument determines the result type, and a union return type forces callers to narrow a result they could have predicted.
Exercise
Why does this compile, and what is the bug? 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); } const d = createDate(2026, 11);
Show answer
It compiles because b and c are optional, so any number of arguments from one to three is allowed. At runtime c is undefined, so the function takes the first branch and returns new Date(2026), which is a date about two seconds after 1970-01-01 (in milliseconds), not a date in 2026. The type allows a call shape the function does not support. Overloads for (timestamp) and (year, month, day) make the two-argument call a compile-time error.