Function overloading is a mechanism or ability to create multiple methods with the same name but different parameter types and return type. However, it can have the same number of parameters. Function overloading is also known as method overloading.
The Function/Method overloading is allowed when:
Suppose we have to perform multiplication of the numbers, which has a different number of parameters. We write the two methods such as mul_a(number, number) for two parameters, and mul_b(number, number, number) for three parameters. Now, it may be difficult for us as well as other programmers to understand the behavior of the method because its name differs. In that case, we need to use function overloading, which increases the readability of the program.
//Function with string type parameter function add(a:string, b:string): string; //Function with number type parameter function add(a:number, b:number): number; //Function Definition function add(a: any, b:any): any { return a + b; } //Result console.log("Addition: " +add("Hello ", "rookienerd")); console.log("Addition: "+add(30, 20));
In the above example:
After compiling the above TypeScript program, we will get the following JavaScript code.
//Function Definition function add(a, b) { return a + b; } //Result console.log("Addition: " + add("Hello ", "rookienerd")); console.log("Addition: " + add(30, 20));
The following example helps to understand the use of method overloading in a class.
class A { public foo(s: string): number; public foo(n: number): string; public foo(arg: any): any { if (typeof(arg) === 'number') return arg.toString(); if (typeof(arg) === 'string') return arg.length; } } let obj = new A(); console.log("Result: " +obj.foo(101)); console.log("Length of String: " +obj.foo("rookienerd"));
After compiling the above TypeScript program, we will get the following JavaScript code.
class A { foo(arg) { if (typeof (arg) === 'number') return arg.toString(); if (typeof (arg) === 'string') return arg.length; } } let obj = new A(); console.log("Result: " + obj.foo(101)); console.log("Length of String: " + obj.foo("rookienerd"));
Function overloading with a different number of parameters and different types along with the same function name is not supported.
function display(x:number, y:number):void //Compiler Error: Duplicate function implementation { console.log(x + x); } function display(x:string): void //Compiler Error: Duplicate function implementation { console.log(x); }