Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to achieve function overloading in TypeScript ?

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.

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.

Javascript




function addData(data1 : string, data2 : string) : string;
  
function addData(data1 : number, data2 : number): number;
  
function addData(data1 : any, data2 : any){
    return data1+ data2;
}
  
console.log(addData("Hello ", "neveropen"));  
console.log(addData(20, 30));


Output:

Hello neveropen
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.

Javascript




class Data
{  
    public displayData(data: string): number;  
    public displayData(data: number): string;  
    public displayData(data : any): any   
    {  
        if (typeof(data) === 'number')  
            return data.toString();  
        if (typeof(data) === 'string')  
            return data.length;  
    }  
}  
  
let object = new Data();  
console.log("Result is : " + object.displayData(123456));
let stringData = "neveropen";  
console.log("Length of String " +  stringData 
    + " is : " + object.displayData(stringData));


Output:

Result is : 123456
Length of String neveropen is : 13

RELATED ARTICLES

Most Popular

Recent Comments