Sunday, 20 January 2013

Method overloading in TypeScript

TypeScript is observed as an object oriented language. Because of which we expect it to behave just like any other object oriented program out there. One of the key features of any object oriented language is method overloading. The way TypeScript supports this feature is a bit different.

In TypeScript, we cannot create multiple methods with same name in a class. If we attempt to do it, we get an error saying Duplicate identifier <Method name>. It happens even if the methods are defined by following all the rules of method overloading.

The way to achieve method overloading in TypeScript is we have to define a method with highest parameters and declare the other methods. Following sample demonstrates it:

class MyClass
{
 Display(num?: number,name?: string){
  document.write("x is: "+num.toString()+" and y is: "+name);
 }
 Display(num: number);
 Display(name: string);
 Display();
}

As we see, we have defined a Display method with two null able parameters and declared three Display methods with one or no parameters. This code compiles to following JavaScript:
var MyClass = (function () {
    function MyClass() { }
    MyClass.prototype.Display = function (num, name) {
        document.write("x is: " + num.toString() + " and y is: " + name);
    };
    return MyClass;
})();

Yes, there is just one function named Display. Because, a JavaScript function can be called passing all or less number of parameters. This applies to constructor as well.
class MyClass
{
 num: number;
 name: string;
 
 constructor(x?: number,str?: string){
  this.num=x;
  this.name=str;
 }
 constructor(x: number);
 constructor(str: string);
 constructor();
}

This compiles to:
var MyClass = (function () {
    function MyClass(x, str) {
        this.num = x;
        this.name = str;
    }
    return MyClass;
})();

It is important to note that the parameters that have to be omitted in overloads should be marked as nullable in the concrete method. Otherwise, the parameter becomes mandatory and TypeScript compiler reports an error.

Happy coding!

No comments:

Post a Comment