Description
Introduction
Currently, in TypeScript, we support only one of the two styles of creating classes in ES6 - that of class declarations. This proposal adds support for the other style, class expressions. This will fill our support for classes in ES6 and help bring us in alignment with both styles.
Class Expressions vs Class Declarations
Class expressions work a little differently than class declarations. Here's a list of the highlights:
- Class expressions have an optional 'BindingIdentifier' or class name. This allows them to create anonymous classes, or name them, as the programmer sees fit.
- Unlike class declarations, class expressions with a name do not introduce this name to the lexical scope outside of the class. The class name of a class expression is only visible inside the body of the class expression.
- Unlike class declarations, class expressions would not create named types in the lexical scope outside of the class. Instead, the named type would only be visible inside the class expression, bound to the class name. Outside of the class expression, they would have anonymous types with the shape of the constructor function.
Just as with class declarations, class expressions would create a constructor function that can be used to construct instances. Like class declarations, you may also declare property members and index members, as well as use the constructor parameters.
Examples
var Rect = class {
area: number;
constructor(public length: number, public width: number) {
this.area = this.length * this.width;
}
}
var rect = new Rect(5, 10);
var MyNode = class Node {
next: Node;
set nextNode(node: Node) {
this.next = node;
}
constructor() { }
}
var node = new MyNode();
var nextNode = new MyNode();
node.nextNode = nextNode;
Emit
Class expressions, just like class declarations, create a constructor function. We would emit them similarly to how we do now, with the exception that they are not immediately bound to a variable. Instead, they create the function expression (IIFE) that builds the constructor function, and allows the developer to assign the result of this expression where appropriate.
Emit of .d.ts
The type emitted for class expressions is the object literal representation of the constructor functions, just as with other anonymous types.
Class expressions can also introduce recursion in the type literal. Anonymous types that have possibly recursive components (like the Node example above) will need special treatment, which should be part of a related spec (Edit: #517).