compiler flag to control property initialization...
I have noticed that the JS code generated from a TS class does not include property initialization inside the constructor function unless the TS class both declares and initializes the properties...although in some regards that makes sense, in others it does not, and it would be great if we could control the compiler in that regard... the main reason I would want the compiler to initialize my properties regardless of whether or not my TS declaration does so is to play nice with the V8 JS engine which uses "hidden classes" to speed up object property access (https://developers.google.com/v8/design)... another reason is to check an object's structure by asking "does this object have this property"... thank you
It's not semantically the same, since Object.prototype.hasOwnProperty will behave differently between an instance with a property that hasn't been set and an instance with an explicit property initialization of undefined.
For instance:
({p: undefined}).hasOwnProperty("p"); // returns true
({}).hasOwnProperty("p"); // returns false
Additionally, we try to avoid generating JS code that doesn't actually have corresponding TS code.
If you're really intent on not explicitly initializing your variables, you could do the following:
class A {
constructor();
constructor(private a?, private b?) {
}
}
where (as you'll see on our playground) your instance members a and b will be initialized to parameters that have the values undefined as long as A's constructor is invoked according to its exposed overload (i.e. new A()).