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

查看:32
本文介绍了类型断言和 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?

推荐答案

区别在于 as Circle 在 TSX 文件中有效,但 与 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 文件中的以下代码:

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

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

会导致如下错误:

错误 TS17002:Circle"应有相应的 JSX 结束标记.

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

但是,as Circle 可以正常工作.

However, as Circle will work just fine.

从现在开始使用 as Circle.这是 推荐 语法.

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

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

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