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?
- You'll have to ask the language designers, everyone else can only speculate. See a similar case.Siguza– Siguza2016-09-03 12:25:16 +00:00Commented Sep 3, 2016 at 12:25
- 2@torazaburo typescript is more than a preprocessor. Look at the compiler's code, it's less a preprocessor and more a language that emits Javascript (which is the 'bytecode' of the javascript VM. If there was anything lower level, it could emit that). It's implemented like many other programming languages.Paarth– Paarth2016-09-03 12:42:13 +00:00Commented Sep 3, 2016 at 12:42
- 1@torazaburo Javascript is turing complete, typescript could simulate anything. That they choose not to is a whole different thing.Alex– Alex2016-09-03 13:09:39 +00:00Commented Sep 3, 2016 at 13:09
- 1@torazaburo Let's not mix our apples and oranges here. Of course TS can't change the nature of the underlying language, but they could emulate any kind of higher level functionality, e.g. proper overloads. But they don't want to, as it's an explicit goal to keep TS close to JS.Alex– Alex2016-09-03 13:36:43 +00:00Commented Sep 3, 2016 at 13:36
- 1@SimonMeskens Not necessarily, TS could as a start insert logic in the constructor/merged function that checks the number of arguments and then executes specific logic accordingly. Then we at least have slightly better overloading based on argument count. And I'm sure we even could have some type checking if we properly give the compiler relevant custom type guards. I'm not saying it's always easy and performant, but nothing is impossible.Alex– Alex2016-09-03 15:57:10 +00:00Commented Sep 3, 2016 at 15:57
2 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.
4 Comments
MyClass function which will override the first .I filed an issue and the outcom is: It would be technically doable, but would break the design goals. Thanks for everyone participating in the discussion.