typescript tslint 指出的“as 语法”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44202311/
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
What is the "as syntax" pointed out by tslint?
提问by k0pernikus
I upgraded tslint and now it complains about:
我升级了 tslint,现在它抱怨:
ERROR: src/Metronome/JobFetcher.ts[13, 32]: Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.
The offending code looks like:
违规代码如下所示:
const jobs = <JobConfig[]> <any> await rp(fetchJobsOptions);
What is the as syntax though and why should I use it?
什么是 as 语法,为什么要使用它?
回答by k0pernikus
Refactor your code like this:
像这样重构你的代码:
const jobs = await rp(fetchJobsOptions) as JobConfig[];
As pointed out in the TypeScript Deep Dive book by Basarat Ali Syed, it says about type casting:
正如Basarat Ali Syed在TypeScript Deep Dive 一书中所指出的,它谈到了类型转换:
as foo vs.
<foo>
Originally the syntax that was added was
<foo>
. This is demonstrated below:var foo: any; var bar = <string> foo; // bar is now of type "string"
However there is an ambiguity in the language grammar when using
<foo> style assertions in JSX: var foo = <string>bar; </string>
Therefore it is now recommended that you just use as foo for consistency.
Type Assertion vs. Casting
The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.
作为 foo vs.
<foo>
最初添加的语法是
<foo>
. 这在下面演示:var foo: any; var bar = <string> foo; // bar is now of type "string"
但是在使用时语言语法存在歧义
<foo> style assertions in JSX: var foo = <string>bar; </string>
因此,现在建议您只使用 as foo 以保持一致性。
类型断言与强制转换
之所以不称为“类型转换”,是因为转换通常意味着某种运行时支持。然而,类型断言纯粹是一种编译时构造,是您向编译器提供有关您希望如何分析代码的提示的一种方式。
回答by Abdulkabir Ojulari
If you want to suppress the error, you can as well go to tslint.json
and include
如果你想抑制错误,你也可以去tslint.json
包括
...
"rules": {
"no-angle-bracket-type-assertion": false,
...
}
...
provided you don't mind consistence as said.
只要你不介意所说的一致性。