gotchatypescriptCritical
Any difference between type assertions and the newer `as` operator in TypeScript?
Viewed 0 times
typescriptassertionsanyandbetweenthedifferenceneweroperatortype
Problem
Is there any difference between what the TypeScript spec calls a type assertion:
And the newer
Both of which are typically used for compile-time casting?
var circle = createShape("circle");And the newer
as operator:var circle = createShape("circle") as Circle;Both of which are typically used for compile-time casting?
Solution
The difference is that
as Circle works in TSX files, but ` conflicts with JSX syntax. as was introduced for this reason.
For example, the following code in a .tsx file:
var 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.Code Snippets
var circle = <Circle> createShape("circle");Context
Stack Overflow Q#33503077, score: 247
Revisions (0)
No revisions yet.