Closed
Description
Summary
We will support inferring the shape of class
es from assignments to properties of this
in the constructor body. Example:
// Was an error, now OK
class Foo {
constructor() {
this.greeting = 'hello!';
}
}
// Also now OK
var x = new Foo();
console.log(x.greeting);
Rules
All or none
If you declare any properties, either using an initializer or non-initialized declaration, you must declare all members this way:
class Alpha {
constructor() {
this.size = 42; // OK
}
}
class Beta {
size: number;
constructor() {
this.siz = 42; // Error
}
}
class Gamma {
size = 100;
constructor() {
this.siz = 42; // Error
}
}
Types of members
The type of each property is the union of all assignment sources:
class Alpha {
constructor() {
this.size = 42;
}
}
var x = new Alpha();
var y = x.size; // y: number
Syntactic forms
Only assignments of the form this.name = expr;
are recognized. Alternate syntax, e.g.this['name'] = expr
, or aliasing of this
(e.g. var x = this; x.foo = bar
) will not create properties.
Open questions:
- Assignment statements only, or all assignment expressions? Chained initialization (
this.x = this.y = 0
) might be common - Do parameter properties count as declared properties?