How to achieve function overloading in TypeScript ?
In this article, we will try to understand some basic details which are associated with the concept of function/method overloading, further will see how we could implement function overloading in TypeScript.
Let us first understand some basic facts involved in function/method Overloading.
- Method overloading is the process in which one method could be used multiple times with same name and different parameter types or return types.
- Function name and number of parameters in overloaded functions should be same.
- Return type of overloaded functions along with data types of parameters could be altered (changed).
- Method Overloading provides code reusability, which saves time and efforts.
- This process also saves memory space, so that the program execution becomes bit faster.
- This process also increases code readability.
After analyzing some of the basic theoretical aspects related to Method Overloading, let us analyze its implementation in TypeScript through the following code examples.
Example 1: In this example we will create several functions (of the same name, but different parameters data types and function’s return type) through which we will add several data passed in by the user of different data types.
Hello GeeksforGeeks 50
Example 2: In this example we will be Implementing function Overloading in a class containing different methods of the same name and different parameter’s data types and method’s return types and further we will be using these methods to print our data in a different manner.
Result is : 123456 Length of String GeeksforGeeks is : 13
Please Login to comment...