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

  1. class Shape { ... }
  2. class Circle extends Shape { ... }
  3. function createShape(kind: string): Shape {
  4. if (kind === "circle") return new Circle();
  5. ...
  6. }
  7. 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:

  1. var shape = createShape(shapeKind);
  2. if (shape instanceof Circle) {
  3. var circle = <Circle> shape;
  4. ...
  5. }

TODO: Document as operator.