4.13 Property Access
A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference.
A dot notation property access of the form
object . name
where object is an expression and name is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time:
- If object is of type Any, any name is permitted and the property access is of type Any.
- Otherwise, if name denotes an accessible apparent property (section 3.11.1) in the widened type (section 3.12) of object, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in 8.2.2.
- Otherwise, the property access is invalid and a compile-time error occurs.
A bracket notation property access of the form
object [ index ]
where object and index are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time:
- If index is a string literal or a numeric literal and object has an apparent property (section 3.11.1) with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property.
- Otherwise, if object has an apparent numeric index signature and index is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature.
- Otherwise, if object has an apparent string index signature and index is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature.
- Otherwise, if index is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.
- Otherwise, the property access is invalid and a compile-time error occurs.
TODO: Indexing with symbols.
The rules above mean that properties are strongly typed when accessed using bracket notation with the literal representation of their name. For example:
var type = {
name: "boolean",
primitive: true
};
var s = type["name"]; // string
var b = type["primitive"]; // boolean
Tuple types assign numeric names to each of their elements and elements are therefore strongly typed when accessed using bracket notation with a numeric literal:
var data: [string, number] = ["five", 5];
var s = data[0]; // string
var n = data[1]; // number