TypeScript Function Overloads
Last Updated :
23 Jan, 2025
Improve
TypeScript function overloads enable defining multiple signatures for a single function, allowing it to handle various parameter types or counts.
- Enhances type safety by ensuring correct argument handling.
- Improves code flexibility and readability.
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));
- 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.
Output:
Hello, Alice!
Hello, Bob! You are 30 years old.
More Example of TypeScript function Overloads
Adding Numbers or Concatenating Strings
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!"));
- 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.
Output:
15
Hello, World!
Fetching Data by ID or Query
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"));
- 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.
Output:
Data for ID: 42
Result for query: search term
Calculating Area for Different Shapes
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));
- 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.
Output:
78.53981633974483
200
Best Practices for Using TypeScript Function Overloads
- Define Clear and Specific Overloads: Ensure each overload signature is precise and unambiguous to enhance code readability and maintainability.
- Order Overloads from Most Specific to Least Specific: Arrange overloads so that more specific signatures appear before more general ones, aiding the TypeScript compiler in selecting the correct overload.
- Implement a Generalized Function Body: The function implementation should accommodate all defined overloads, using type guards or conditional logic to handle different parameter types appropriately.