Typescript function overloading
Created By: chatGPT
TypeScript supports function overloading, allowing you to define multiple function signatures for a single function. This can make your code more flexible and expressive. Each signature defines how the function can be called with different sets of parameters, and you implement one standard function that manages the behavior for all these cases.
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}!`;
}
In the example above, we define two overload signatures for the
greet
function. The first signature accepts a single string argument, while the second accepts a string and a number. Below the overloads, we implement the actual function, which checks if the second parameter (age
) is provided. If so, it returns a greeting with age included; otherwise, it returns a simple greeting.const greeting1 = greet('Alice'); // Returns 'Hello Alice!'
const greeting2 = greet('Bob', 25); // Returns 'Hello Bob, you are 25 years old!'
Function overloading is particularly useful when the same function can have different meanings based on the types and number of its parameters. This allows for better type checking and documentation within the code, leading to more maintainable and readable applications.
function calculatearea(width: number, height: number): number;
function calculatearea(side: number): number;
function calculatearea(width: number, height?: number): number {
if (height !== undefined) {
return width * height; // Rectangle
}
return width * width; // Square
}