Skip to content

Add support for prototype-based property default values #15607

@Fruneau

Description

@Fruneau

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ExternalRelates to another program, environment, or user action which we cannot control.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions