I come from C# development background, and thus things like method overloading comes to my mind naturally when tackling a certain type of problem. However, when coding in languages like JavaScript, this becomes a problem.
As TypeScript compiles into JavaScript, this becomes a problem of TypeScript as well. One can eventually achieve function overloading in TypeScript but it is quite a work and frankly a bit awkward.
However if you absolutely have to do Function overloading in typescript, here is how to do it. Lets say you have function called testFunction and you want to overload it n times. Then you have to define this function n+1 times. Here is the code snippet of function testFunction with two overloads.
1:
2: testFunction(param1: string ,param2:string):void;
3: testFunction(param1:string,param2:number):void;
4:
5: testFunction(param1:string,param2:any):void{
6: if(typeof param2=="string"){
7: //Do what you want to do in first function
8: }
9: else if(typeof param2=="number"){
10: //Do what you want to do in second function
11: }
12: }
So basically first you have to declare both the function and then write third function that checks which function is called based on the type of the parameter.
Now lets say you have to do it with one and two parameters respectively. That is also possible -
1: testFunction(param1:number):void;
2: testFunction(param1:string,param2:string):void;
3:
4: testFunction(param1:any,param2?:string):void{
5: if(typeof param1 =="number"){
6: //Do what you want to do in first function
7: }
8: else if(param2&&typeof param2 =="string"){
9: //Do what you want to do in second function
10: }
Posted
Feb 15 2017, 02:37 PM
by
Indraneel Pole