How to do function overloading in TypeScript?

TypeScript supports function overloading based on a number of parameters. The function overloading is quite different compare to other object-oriented languages.

Following is an example of TypeScript function overloading:

  class User {
    getAttr(attr: string);
    getAttr(attr: number);
    getAttr(attr: number, secondAttr: string);
    getAttr(attr: any, secondAttr?: string) {
      console.log(attr.toString());
    }
  }

What we are doing here is, we are creating just one function and a number of declarations so that TypeScript doesn’t give compile errors.

When this code is compiled to JavaScript by TypeScript, There will be only one function like below:

var User = /** @class */ (function () {
    function User() {
    }
    User.prototype.getAttr = function (attr, secondAttr) {
        console.log(attr.toString());
    };
    return User;
}());

JavaScript function can be called by passing multiple arguments.