Function overloading allows a function to have multiple call signatures with different parameter types or counts while sharing a single implementation.
- Define multiple ways to call the same function.
- Improve type safety with different parameter combinations.
- Enhance code readability and reusability.
- Maintain a single implementation for all overloads.
Examples of Function Overloading
The following examples demonstrate how function overloading supports different parameter types and argument combinations using a single implementation.
Example 1: Greeting Function
Function overloading allows a function to support 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("Alen"));
console.log(greet("Ben", 30));
Output:
Hello, Alen!
Hello, Ben! You are 30 years old.
- greet has two overload signatures.
- One overload accepts only person, while the other accepts both person and age.
- A single implementation handles both cases.
Example 2: Adding Numbers or Concatenating Strings
Function overloading enables a function to work with different parameter types.
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!
- combine supports both number and string parameters.
- The implementation performs addition or concatenation based on the argument types.
Example 3: Fetching Data by ID or Query
Function overloading allows different return types based on the input parameters.
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' ]
- fetchData accepts either a numeric ID or a string query.
- The return type depends on the selected overload.
- A single implementation handles both scenarios.
Example 4: Calculating Area for Different Shapes
Function overloading enables a function to perform different operations based on the number of arguments.
function calculateArea(radius: number): number;
function calculateArea(length: number, width: number): number;
function calculateArea(value1: number, value2?: number): number {
if (value2 === undefined) {
return Math.PI * value1 ** 2;
}
return value1 * value2;
}
Output:
78.53981633974483
200
- calculateArea supports both one and two arguments.
- One argument calculates the area of a circle.
- Two arguments calculate the area of a rectangle.