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?
In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.
error TS2392: Multiple constructor implementations are not allowed.
But in TypeScript, unlike any other object-oriented language, only one constructor is allowed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With