类型断言与TypeScript中较新的`as`运算符之间有何区别? [英] Any difference between type assertions and the newer `as` operator in TypeScript?

查看:343
本文介绍了类型断言与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");

将导致以下错误:


错误TS17002:预期'Circle'对应的JSX结束标记。

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

但是,作为Circle 可以正常工作。

从现在开始使用作为Circle 。这是推荐语法。

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

这篇关于类型断言与TypeScript中较新的`as`运算符之间有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆