什么是“as 语法"?tslint 指出的? [英] What is the "as syntax" pointed out by tslint?
问题描述
我升级了 tslint,现在它抱怨:
I upgraded tslint and now it complains about:
ERROR: src/Metronome/JobFetcher.ts[13, 32]: Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.
违规代码如下:
const jobs = <JobConfig[]> <any> await rp(fetchJobsOptions);
as 语法是什么,我为什么要使用它?
What is the as syntax though and why should I use it?
推荐答案
像这样重构你的代码:
const jobs = await rp(fetchJobsOptions) as JobConfig[];
正如 Basarat Ali Syed 在 TypeScript Deep Dive 书中所指出的,它说的是类型转换:
As pointed out in the TypeScript Deep Dive book by Basarat Ali Syed, it says about type casting:
最初添加的语法是
.这证明下面:
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>
因此现在建议您只使用 as foo for一致性.
Therefore it is now recommended that you just use as foo for consistency.
不叫类型转换"的原因是转换通常意味着某种运行时支持.然而类型断言纯粹是一种编译时构造,也是一种方式向编译器提供有关您希望代码如何的提示分析.
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.
这篇关于什么是“as 语法"?tslint 指出的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!