类型断言和 TypeScript 中较新的 `as` 运算符之间有什么区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33503077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:48:51  来源:igfitidea点击:

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

castingtypescript

提问by mk.

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

TypeScript 规范所称的类型断言之间有什么区别:

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

And the newerasoperator:

较新的as运营商:

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

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

这两个通常用于编译时强制转换?

回答by David Sherret

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

不同之处在于它as Circle适用于 TSX 文件,但<Circle>与 JSX 语法冲突。as为此而推出。

For example, the following code in a .tsxfile:

例如,.tsx文件中的以下代码:

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

Will result in the following error:

会导致以下错误:

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

错误 TS17002:“Circle”应有相应的 JSX 结束标记。

However, as Circlewill work just fine.

但是,as Circle会工作得很好。

Use as Circlefrom now on. It's the recommendedsyntax.

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

回答by Martin Vseticka

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

来自Wiki 页面:“TypeScript [1.6] 中的新功能”:

New .tsxfile extension and asoperator

TypeScript 1.6 introduces a new .tsxfile extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the new asoperator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:

var x = <any> foo; 
// is equivalent to:
var x = foo as any;

新的.tsx文件扩展名和as运算符

TypeScript 1.6 引入了新的.tsx文件扩展名。这个扩展做了两件事:它在 TypeScript 文件中启用 JSX,它使 newas操作符成为默认的转换方式(消除 JSX 表达式和 TypeScript 前缀转换操作符之间的任何歧义)。例如:

var x = <any> foo; 
// is equivalent to:
var x = foo as any;