-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Add support for prototype-based property default values #15607
Description
Currently when defining a class, the default values assigned to property are set by the constructor of the class:
class A {
map: { [key: string]: string } = {};
}Generates the following code:
class A {
constructor() {
this.map = {};
}
}This has its advantages: each instance of the class has its own instance of the field. However, it also has some surprising effects when the value is the result of a more complex expression, or in case we want the variable to refer to a shared instance. As a consequence, writing code that share an instance requires either to use a separate variable or manually patch the prototype after creating the class:
Using a separate variable:
const sharedMap: { [key: string]: string } = {};
class A {
map = sharedMap;
}Manually patching the prototype:
class A {
map: { [key: string]: string };
}
A.prototype.map = {}My proposal would be to add a new property modifier that would define a default value as shared between the instances.
class A {
prototype map: { [key: string]: string } = {}
}That code would be equivalent to the "Manual patching" case. The new keyword prototype could only be used on variables with a default value since it would only affect the storage of the default value.