Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no overloaded constructor implementations in TypeScript?

In TypeScript it's only possible to overload the constructor type signatures, but not the Implementation. Is there and reason behind this? Overloading constructors like in Java are really useful I think. For example a definition for vectors could be the end cordinates, or start and endpoint or two vectors and so on. The current approach in TypeScript is very chaotic. So why doesn't typescript have it?

like image 803
sclausen Avatar asked Sep 03 '16 12:09

sclausen


People also ask

Is constructor overloading possible in TypeScript?

In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.

Can we have multiple constructors in angular?

error TS2392: Multiple constructor implementations are not allowed.

How many constructors can a class have in TypeScript?

But in TypeScript, unlike any other object-oriented language, only one constructor is allowed.

Can you overload constructors in JavaScript?

No you can't, JavaScript does not support overloading of any kind. What you can do is either pass an object which has already been populated with the values into your constructor and then grab the values from the object, but this which duplicates code.


1 Answers

Yes, there's a reason for it, and the reason is that javascript does not support using the same name for a method or a member.

Consider the following typescript:

class MyClass {
    myMethod() {}
    myMethod(str: string) {}
}

The compiled version is:

var MyClass = (function () {
    function MyClass() {
    }
    MyClass.prototype.myMethod = function () { };
    MyClass.prototype.myMethod = function (str) { };
    return MyClass;
}());

As you can see, the 2nd implementation of myMethod is replacing the first implementation.
Because of that you can only overload the signatures and then you need to provide a single implementation which satisfies all of the declared signatures.

like image 102
Nitzan Tomer Avatar answered Oct 23 '22 05:10

Nitzan Tomer