TypeScript supports function overloading, a feature that allows the same function name to handle multiple parameter lists. However, to implement function overloading, we need to define overload signatures and an implementation that is compatible with all of them.
Let me provide a simple example to illustrate this concept:
Suppose we have a function getInfo that can accept either a number or a string as a parameter. If it's a number, we assume it represents the user's ID and return the user's detailed information; if it's a string, we assume it represents the user's name and return the user's introduction.
Here's how we can define the overloads:
typescript// Function overload signatures function getInfo(id: number): string; // When passing a number, fetch user details function getInfo(name: string): string; // When passing a string, fetch user introduction // Function implementation function getInfo(data: any): string { if (typeof data === "number") { return `Fetching user details for ID: ${data}`; } else if (typeof data === "string") { return `Fetching user intro for name: ${data}`; } throw new Error("Function must be called with either a string or a number"); } // Using the function overloading console.log(getInfo(101)); // Output: Fetching user details for ID: 101 console.log(getInfo("John")); // Output: Fetching user intro for name: John
In this example, we first define two function signatures: one that accepts a number parameter and another that accepts a string parameter. Then we implement a getInfo function using a more permissive parameter type any to handle the specific functionality. Inside the function, we use typeof checks to determine the processing logic.
By doing this, we can clearly inform developers who use this function about the expected parameter types and the different operations performed based on the parameter type, while maintaining the consistency of the function name, thereby improving code readability and maintainability.