Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

typescript - What is the "as syntax" pointed out by 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.

The offending code looks like:

const jobs = <JobConfig[]> <any> await rp(fetchJobsOptions);

What is the as syntax though and why should I use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...