Any difference between type assertions and the newer `as` operator in TypeScript?

CastingTypescript

Casting Problem Overview


Is there any difference between what the TypeScript spec calls a type assertion:

var circle = <Circle> createShape("circle");

And the newer as operator:

var circle = createShape("circle") as Circle;

Both of which are typically used for compile-time casting?

Casting Solutions


Solution 1 - Casting

The difference is that as Circle works in TSX files, but <Circle> conflicts with JSX syntax. as was introduced for this reason.

For example, the following code in a .tsx file:

var circle = <Circle> createShape("circle");

Will result in the following error:

> error TS17002: Expected corresponding JSX closing tag for 'Circle'.

However, as Circle will work just fine.

Use as Circle from now on. It's the recommended syntax.

Solution 2 - Casting

From Wiki page: "What's new in TypeScript [1.6]":

> New .tsx file extension and as operator > > TypeScript 1.6 introduces a new .tsx file extension. This extension > does two things: it enables JSX inside of TypeScript files, and it > makes the new as operator the default way to cast (removing any > ambiguity between JSX expressions and the TypeScript prefix cast > operator). For example: > > var x = foo; > // is equivalent to: > var x = foo as any;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmk.View Question on Stackoverflow
Solution 1 - CastingDavid SherretView Answer on Stackoverflow
Solution 2 - CastingMartyIXView Answer on Stackoverflow