打字稿Symbol.iterator

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中的错误还是我错过了什么?

谢谢

Mad*_*iha 7

这不是一个bug.这取决于你的目标.

TypeScript做了一个(在我看来很可怕)设计决策,如果你将TS转换for..of为ES5或ES3,它会发出一个正常的for (var i; i < testingIterables.length; i++)循环.

因此,对于目标ES5和ES3,for..of循环中只允许使用数组和字符串.

有几种方法可以解决这个问题:

  • 如果你的TypeScript超过2.3,你可以将downlevelIteration标志设置为true,这将导致TypeScript正确编译迭代器,但这意味着你必须在运行时为非支持浏览器设置一个Symbol.iterator polyfill,否则你可能会出现意外的运行时错误那些浏览器的地方.
  • 选择更高的目标,ES2015或更高的目标将起作用.然后你可以使用Babel进一步向下转换(你还需要一个运行时polyfill来使Symbols工作)
  • 使用while和调用自己展开迭代器testingIterables.next().