TypeScript Function Overloads
TypeScript Function Overloads allow us to define multiple ways a function can be called, with different parameter types or counts, while keeping a single implementation. This helps create flexible, type-safe APIs that improve code readability and developer experience.
Example 1: Greeting Function
This example shows how overloads handle functions with different numbers of parameters.
function greet(person: string): string;
function greet(person: string, age: number): string;
function greet(person: string, age?: number): string {
if (age !== undefined) {
return `Hello, ${person}! You are ${age} years old.`;
}
return `Hello, ${person}!`;
}
console.log(greet("Alice"));
console.log(greet("Bob", 30));
Output:
Hello, Alice!
Hello, Bob! You are 30 years old.
In this example:
- The function greet has two overloads: one with a single parameter person and another with person and age.
- The implementation checks if age is provided and returns an appropriate greeting.
Example 2: Adding Numbers or Concatenating Strings
Demonstrates how overloads handle both numeric addition and string concatenation.
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any): any {
return a + b;
}
console.log(combine(5, 10));
console.log(combine("Hello, ", "World!"));
Output:
15
Hello, World!
In this example:
- The combine function is overloaded to handle both numbers and strings, either adding or concatenating them.
- The implementation uses a single function to manage both scenarios.
Example 3: Fetching Data by ID or Query
Shows how overloads can distinguish between numeric IDs and string queries.
function fetchData(id: number): string;
function fetchData(query: string): string[];
function fetchData(param: any): any {
if (typeof param === 'number') {
return `Data for ID: ${param}`;
} else {
return [`Result for query: ${param}`];
}
}
console.log(fetchData(42));
console.log(fetchData("search term"));
Output:
Data for ID: 42
[ 'Result for query: search term' ]
In this example:
- The fetchData function is overloaded to accept either a numeric ID or a string query.
- It returns a string for an ID and an array of strings for a query.
Example 4: Calculating Area for Different Shapes
Illustrates overloads for handling both circles and rectangles.
function calculateArea(radius: number): number;
function calculateArea(length: number, width: number): number;
function calculateArea(...args: number[]): number {
if (args.length === 1) {
return Math.PI * args[0] ** 2;
} else {
return args[0] * args[1];
}
}
console.log(calculateArea(5));
console.log(calculateArea(10, 20));
Output:
78.53981633974483
200
In this example:
- The calculateArea function is overloaded to compute the area of a circle when given one argument and a rectangle when given two arguments.
- It uses rest parameters to handle a varying number of arguments.