Yar*_*atz 6 iterator iterable typescript ecmascript-6
我正在尝试创建自定义迭代.
这是我的代码的简化示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
此代码将在ES6上正确运行,但使用TypeScript,它将编译而不打印可迭代值.
这是TypeScript中的错误还是我错过了什么?
谢谢
这不是一个bug.这取决于你的目标.
TypeScript做了一个(在我看来很可怕)设计决策,如果你将TS转换for..of为ES5或ES3,它会发出一个正常的for (var i; i < testingIterables.length; i++)循环.
因此,对于目标ES5和ES3,for..of循环中只允许使用数组和字符串.
有几种方法可以解决这个问题:
downlevelIteration标志设置为true,这将导致TypeScript正确编译迭代器,但这意味着你必须在运行时为非支持浏览器设置一个Symbol.iterator polyfill,否则你可能会出现意外的运行时错误那些浏览器的地方.while和调用自己展开迭代器testingIterables.next().| 归档时间: |
|
| 查看次数: |
2092 次 |
| 最近记录: |