4.16 Type Assertions
TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression:
UnaryExpression: ( Modified ) … <
Type >
UnaryExpression
A type assertion expression consists of a type enclosed in <
and >
followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are not checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing <
and >
are simply removed from the generated code.
In a type assertion expression of the form < T > e, e is contextually typed (section 4.23) by T and the resulting type of e is required to be assignable to T, or T is required to be assignable to the widened form of the resulting type of e, or otherwise a compile-time error occurs. The type of the result is T.
Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that might be correct, but aren’t known to be correct. In the example
class Shape { ... }
class Circle extends Shape { ... }
function createShape(kind: string): Shape {
if (kind === "circle") return new Circle();
...
}
var circle = <Circle> createShape("circle");
the type annotations indicate that the ‘createShape’ function might return a ‘Circle’ (because ‘Circle’ is a subtype of ‘Shape’), but isn’t known to do so (because its return type is ‘Shape’). Therefore, a type assertion is needed to treat the result as a ‘Circle’.
As mentioned above, type assertions are not checked at run-time and it is up to the programmer to guard against errors, for example using the instanceof
operator:
var shape = createShape(shapeKind);
if (shape instanceof Circle) {
var circle = <Circle> shape;
...
}
TODO: Document as operator.