问题
I'm trying to create a custom iterable.
here is a simplified example of my code:
class SortedArray {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
return 4;
}
}
const testingIterables = new SortedArray();
for(let item of testingIterables as any) { // i have to cast it as any or it won't compile
console.log(item);
}
This code will run correctly on ES6 but with TypeScript it will compile and not print the iterable values.
Is this a bug in TypeScript or am I missing something?
Thanks
回答1:
It isn't a bug. It depends on your target.
TypeScript made a (terrible, in my opinion) design decision that if you transpile TS for..of
to ES5 or ES3, it emits a normal for (var i; i < testingIterables.length; i++)
loop.
For that reason, for targets ES5 and ES3, only arrays and strings are allowed in for..of
loops.
There are several options to remedy this:
- If your TypeScript is over 2.3, you can set the
downlevelIteration
flag to true, this will cause TypeScript to compile iterator correctly, but it means you must have a Symbol.iterator polyfill in runtime for non-supporting browsers, else you risk runtime errors in unexpected places for those browsers. - Select a higher target, ES2015 or higher would work. You can then transpile further down with the use of Babel (you'll also need a runtime polyfill to make Symbols work)
- Unwrap the iterator yourself with the use of
while
and calls totestingIterables.next()
.
来源:https://stackoverflow.com/questions/48590262/typescript-symbol-iterator