TypeScript Function Overloads
Function overloads let you describe a function that can be called in multiple different ways, each with different parameter types or counts, while still having one actual implementation.
You write several overload signatures above the real function body. TypeScript uses these signatures to check calls, while the final implementation signature must be general enough to handle every overload.
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
return a + b;
}Writing overload signatures
Each overload signature declares a specific combination of parameter types and a return type, without a function body. They appear directly above the implementation.
The implementation signature
The final function definition contains the actual logic and must accept every possible combination of parameters described by the overloads, often using union types internally.
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
return a + b;
}
console.log(combine(1, 2));
console.log(combine("a", "b"));3
abTypeScript picks the matching overload based on the argument types used at each call site.
function makeArray(x: number): number[];
function makeArray(x: string): string[];
function makeArray(x: any): any {
return [x, x, x];
}
console.log(makeArray(5));
console.log(makeArray("hi"));[ 5, 5, 5 ]
[ 'hi', 'hi', 'hi' ]Each overload tells callers exactly what return type to expect for a given input type.
Key points
- Overloads let a single function support multiple call signatures.
- Overload signatures are written above the actual implementation.
- The implementation signature must cover every overload's parameter types.
- Callers see only the specific overloads, not the general implementation signature.
