What is a Function Overload?
TypeScript function overloads allow you to define multiple function signatures for the same function. This helps TypeScript understand different valid ways a function can be called, while keeping strong type safety.
At runtime, only one function implementation exists.
Basic Syntax
A function overload consists of:
- Overload signatures (no body)
- Single implementation
// Overload signatures
function add(a: number, b: number): number;
function add(a: string, b: string): string;
// Implementation
function add(a: any, b: any) {
return a + b;
}
Usage
add(2, 3); // number
add("a", "b"); // string
add(2, "b"); // Error
Example 1: Different Number of Parameters
function greet(name: string): string;
function greet(firstName: string, lastName: string): string;
function greet(a: string, b?: string) {
return b ? `Hello ${a} ${b}` : `Hello ${a}`;
}
greet("John");
greet("John", "Doe");
Example 2: Different Return Types
function parseInput(value: string): string;
function parseInput(value: number): number;
function parseInput(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
parseInput("hello"); // string
parseInput(10); // number
Example 3: Object-Based Overloads
type User = { id: number; name: string };
function getUser(id: number): User;
function getUser(user: User): string;
function getUser(value: number | User) {
if (typeof value === "number") {
return { id: value, name: "Guest" };
}
return value.name;
}
Overloads vs Union Types
Without Overload
function combine(a: string | number, b: string | number) {
return a + b;
}
Return type becomes string | number (less precise).
With Overload
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any) {
return a + b;
}
Precise return types are preserved.
Rules to Remember
- Overload signatures have no implementation
- Only one implementation is allowed
- The implementation signature is not visible to callers
- Implementation must support all overloads
When to Use Function Overloads
Use when:
- Return type depends on input type
- Number of parameters varies
- Designing public APIs
Avoid when:
- Union types are sufficient
- Logic is simple
Summary
| Feature | Description |
|---|---|
| Purpose | Multiple valid call signatures |
| Runtime | Single JS function |
| Benefit | Better type safety & IntelliSense |
| Alternative | Union types |
Top comments (0)