TypeScript Version: 3.5.0-dev.20190418
Search Terms: typescript quoted constructor
Code
class Foo {
constructor(name: string) {
this.name = name
}
}
class Bar {
"constructor"(name: string) {
this.name = name
}
}
new Foo("hello")
new Bar("hello")
Expected behavior:
Compiles without error
Actual behavior:
The new Foo call compiles properly, but the new Bar call produces a type checking error:
test.ts:9:9 - error TS2554: Expected 0 arguments, but got 1.
9 new Bar("hello")
~~~~~~~
Note that running the code (with the type assertions stripped) results in both constructors being called, but TypeScript鈥檚 ES5 transpilation instead sets the second constructor as a method named constructor, which causes it not to be run.
Playground Link: Open playground 鈫楋笍
Related Issues: Encountered in https://github.com/prettier/prettier/issues/6063.
The second code snippet does not create a constructor, it creates a property named constructor.
If you expect otherwise, then how would you expect to be able to define a property with that name?
edit: Tho it seems that in JavaScript it works as you expect it. Really weird.
We guessed wrong what the ES class semantics would be, which is pretty unfortunate now.
Not clear how to proceed since this will be a runtime breaking change for people who chose their method/property names extremely poorly.
Plan: Issue an error in 3.5 if we see this and target is <= ES5, then change the ES5 emit in 3.6.
Plan: Issue an error in 3.5 if we see this and target is <= ES5, then change the ES5 emit in 3.6.
Moving the milestone since the grammar error part is done. This issue now tracks
change the ES5 emit
Most helpful comment
Plan: Issue an error in 3.5 if we see this and
targetis<= ES5, then change the ES5 emit in 3.6.