本文介绍了类型断言与TypeScript中较新的`as`运算符之间有何区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TypeScript规范称为类型断言之间是否有任何区别:
Is there any difference between what the TypeScript spec calls a type assertion:
var circle = <Circle> createShape("circle");
和 as
运算符:
var circle = createShape("circle") as Circle;
两者通常都用于编译时转换吗?
Both of which are typically used for compile-time casting?
推荐答案
区别在于 Circle
在TSX文件中有效,而< Circle> ;
与JSX语法冲突。出于这个原因引入了 as
。
The difference is that as Circle
works in TSX files, but <Circle>
conflicts with JSX syntax. as
was introduced for this reason.
例如,中的以下代码。 tsx
文件:
var circle = <Circle> createShape("circle");
将导致以下错误:
但是,作为Circle
可以正常工作。
从现在开始使用作为Circle
。这是语法。
Use as Circle
from now on. It's the recommended syntax.
这篇关于类型断言与TypeScript中较新的`as`运算符之间有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!