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
1.2k views
in Technique[技术] by (71.8m points)

typescript - Why `downlevelIteration` is not on by default?

When targeting ES5 with usage of spread operator ... to convert an Iterator to an Array, it shows the error to use -downlevelIteration compiler option. Once it is on, spread operators seem just work flawlessly.

I wonder why is there a need to specify this? Are there any downsides/limitation when it is enabled besides adding more emitted generated code from tslib?

Another example: Dynamically create array of N (eg. 3):

[...Array(3).keys()]  // output: [0, 1, 2]

It displays an error in VS Code:
enter image description here

Error message from tsc:

Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

Edit and view the code and error in TypeScript Playground

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

After reading the release notes and the article Downlevel Iteration for ES3/ES5 in TypeScript, I believe the answer to this question is that downlevelIteration is disabled because you need to decide (via configuration) how you want TypeScript to handle the compilation of compatibility code (to support older versions of Javascript).

As the more lengthy explanation in the article makes clear, you have to make a decision as to if you want TypeScript to inline necessary helper functions (simple, but can result in larger production bundle size) or if you wish to configure TypeScript to use tslib as a dependency and then make calls to its external methods.

I highly recommend reading Downlevel Iteration for ES3/ES5 in TypeScript for a deeper understanding… and possibly an alternate solution to your initial issue.


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

...