Skip to content

ES6 Computed Properties #1082

Closed
Closed
@JsonFreeman

Description

@JsonFreeman

ES6 allows an arbitrary expression as the name of a property. The syntax is like this:

var x = {
   ["some" + "arbitrary" + "name"]: 0
}

Here is my current proposal for supporting this feature:

Computed expressions would be allowed in the following places if target is ES6:

  • Object literal properties
  • Class methods and accessors (both static and instance), but not property declarations.
  • 'this' references are not allowed in computed properties.
  • No parameter properties
  • Do not allow in interfaces
  • No enum members

Below ES6:

  • Computed properties are not allowed

Note that emit for all of the above is straightforward.

Type check:

  • All computed names must be of type string, number, or any (or eventually symbol)
  • No property will be added to the containing type based on a computed name.
  • Computed names that are not well known do not add a property to the type, but they will be included in the union type for the indexer, if the containing type has an indexer.

Questions:

  • Should an unknown name cause the surrounding type to have an indexer, if it wouldn't have acquired one otherwise? Our decision here is 'no'. Here is an argument for and against:

Argument for - we would want this to work:

var n = "some " + "unknown " + "name";
var obj = {
    [n]: 0;
};
var num = obj[n]; // This should be number

Argument against - Computed properties would be allowed in class properties, so someone might have a class hierarchy like this:

var n = "some " + "unknown " + "name";
class C {
    [n]: number;
}
class D extends C {
   foo: string; // Error because C was given an implicit indexer that D inherited, but foo doesn't conform to the indexer
}

Metadata

Metadata

Assignees

Labels

SpecIssues related to the TypeScript language specification

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions