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:
Error message from tsc
:
Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
ベストアンサー1
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.