Sub topic 2
Writing TypeScript Overload Signatures
Assume you know basic TypeScript types, unions, literal types, typed functions, type narrowing with typeof and Array.isArray, and the basics of classes and interfaces.
A function overload lets one function support several documented call shapes. A call shape is a particular combination of argument types and count. Each shape can have its own return type.
Overloads are useful when the return type depends on the arguments. For example, a function that receives a string can return a string[], while the same function receiving a number can return a number[].
The two parts of an overload
A TypeScript overload has two parts:
- One or more overload signatures. These describe the calls that callers may make.
- One implementation signature. This contains the function body and handles all supported cases.
The overload signatures come first. They have no function body. The implementation signature comes last and has the body.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const words = toArray("hello");
const numbers = toArray(42);
console.log(words); // ["hello"]
console.log(numbers); // [42]The first signature says that a string argument produces a string[]. The second says that a number argument produces a number[]. The implementation accepts string | number, because its body must handle both inputs.
The return type of the implementation is (string | number)[], which is broad enough to contain either result. Callers do not see this broad return type. They see the return type from the overload that matches their call.
Matching parameters and return types
Each overload signature should describe a behavior that the implementation really supports. The parameter types must cover every input accepted by the overloads. The implementation must also return values compatible with the overload return types.
Consider a function that formats either a number or a date:
function formatValue(value: number): string;
function formatValue(value: Date): string;
function formatValue(value: number | Date): string {
if (typeof value === "number") {
return value.toFixed(2);
}
return value.toISOString();
}
console.log(formatValue(12.5)); // "12.50"
console.log(formatValue(new Date("2026-11-25"))); // ISO date stringBoth overloads return string, so the implementation can use string as its return type. Its parameter is a union because the body receives either a number or a date.
The body still needs narrowing. A union type tells TypeScript that a value may have several types. Narrowing is the process of checking which type the value has before using type-specific operations. Here, typeof value === "number" narrows the value to number. The remaining branch treats it as Date.
The implementation must cover every overload
The implementation signature cannot be narrower than an overload signature. If an overload accepts a string, the implementation must accept strings too.
function repeat(value: string): string;
function repeat(value: number): number;
// Error: the implementation cannot accept all overload inputs.
// function repeat(value: number): string | number {
// return value;
// }This implementation cannot support the first overload because it accepts only numbers. A compatible implementation could use a union:
function repeat(value: string): string;
function repeat(value: number): number;
function repeat(value: string | number): string | number {
if (typeof value === "string") {
return value + value;
}
return value * 2;
}
console.log(repeat("ab")); // "abab"
console.log(repeat(5)); // 10The implementation return type must also be broad enough. It returns either string or number, so string | number is appropriate.
However, the implementation signature does not promise that every input produces every member of its return union. The overloads provide the precise public promises:
- A string call returns a string.
- A number call returns a number.
The implementation body is responsible for keeping those promises true.
Overloads do not make invalid calls valid
Only the declared overload signatures are available to callers. If no overload accepts a call, TypeScript reports an error.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const value = Math.random() > 0.5 ? "x" : 1;
// Error: no overload matches this call.
// The value has type string | number.
const result = toArray(value);The implementation accepts string | number, but that fact does not create a public union overload. Add one when callers may legitimately provide a union:
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const value = Math.random() > 0.5 ? "x" : 1;
const result = toArray(value);
console.log(result);The added overload explicitly documents what happens for a union argument. Its return type is broad because TypeScript cannot know which member the value contains at runtime.
A model for writing overloads
Use this sequence when designing an overloaded function:
flowchart TD
A[Identify supported call shapes] --> B[Write one overload per public shape]
B --> C[Choose implementation parameter types]
C --> D[Write narrowing logic]
D --> E[Choose a compatible implementation return type]
E --> F[Test each overload and invalid calls]The overload signatures form the public API. The implementation signature forms the internal working model.
Start with the calls you want users to write. For example, a date factory may accept either a timestamp or separate date parts:
function createDate(timestamp: number): Date;
function createDate(year: number, month: number, day: number): Date;
function createDate(
first: number,
second?: number,
third?: number
): Date {
if (second === undefined || third === undefined) {
return new Date(first);
}
return new Date(first, second - 1, third);
}
const fromTimestamp = createDate(0);
const fromParts = createDate(2026, 11, 25);
console.log(fromTimestamp.toISOString());
console.log(fromParts.toISOString());The overloads allow one argument or three arguments. The implementation uses optional parameters because it must handle both forms. An optional parameter is a parameter that may be omitted, so its value can be undefined.
The implementation checks the arguments before using them. Without that check, TypeScript would correctly reject arithmetic involving possibly undefined values.
Writing useful overloads
An overload should describe a meaningful difference in behavior or in the type information available to the caller. Do not add overloads merely because two calls use different literal values if both calls have the same useful return type.
For example, this function does not need overloads:
function getLength(value: string | readonly unknown[]): number {
return value.length;
}
console.log(getLength("TypeScript"));
console.log(getLength([1, 2, 3]));Both input forms produce the same return type, number, so a union is simpler.
A generic is often better when the function preserves a type instead of changing behavior based on a fixed set of input types:
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const firstName = first(["Ada", "Lin"]);
const firstScore = first([10, 20]);
console.log(firstName); // string | undefined
console.log(firstScore); // number | undefinedA generic type parameter, T, represents a type chosen by the caller. The function returns the same element type that it receives.
Use overloads when the function has a small, distinct set of public call shapes and those shapes provide different type information. Use a union when the behavior and return type are the same for all input types. Use a generic when the function preserves a relationship between input and output types.
Exercise
Write overloads for a function named parseId that accepts a string and returns a number, or accepts a readonly string array and returns a number array. Add an implementation that uses Array.isArray.
Show answer
function parseId(value: string): number; function parseId(value: readonly string[]): number[]; function parseId(value: string | readonly string[]): number | number[] { return Array.isArray(value) ? value.map(Number) : Number(value); }