打字稿Symbol.iterator [英] typescript Symbol.iterator
问题描述
我正在尝试创建自定义迭代。
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);
}
这段代码可以在ES6上正确运行但是使用TypeScript它会编译而不能打印可迭代的值。
This code will run correctly on ES6 but with TypeScript it will compile and not print the iterable values.
这是TypeScript中的错误还是我错过了什么?
Is this a bug in TypeScript or am I missing something?
谢谢
推荐答案
这不是错误。这取决于你的目标。
It isn't a bug. It depends on your target.
如果你将TS 转换为...的话,TypeScript做出了一个(在我看来很糟糕)的设计决定
。
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.
因此,对于目标ES5和ES3, for..of
循环中只允许使用数组和字符串。
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:
- 如果你的TypeScript超过2.3,你可以设置
downlevelIteration
标志为true,这将导致TypeScript正确编译迭代器,但这意味着您必须在运行时为不支持的浏览器设置Symbol.iterator polyfill ,否则在这些浏览器的意外位置存在运行时错误。
- 选择更高的目标,ES2015或更高版本可行。然后你可以使用Babel进一步向下传递(你还需要一个运行时polyfill来使Symbols工作)。
- 使用
自行打开迭代器而
并调用 testingIterables.next()
。
- 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 to testingIterables.next()
.
这篇关于打字稿Symbol.iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!