Skip to content

Class property inference from constructor initializations in JavaScript #4955

Closed
@RyanCavanaugh

Description

@RyanCavanaugh

Summary

We will support inferring the shape of classes 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?

Other issues mentioning this: #766, #2393, #2606.

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions