Generators in Typescript `for...of` loop

Viewed 2315

I am trying to get Typescript to compile the following generator-loop correctly, which in a modern browser works as expected:

/** Should print "x= 1 y= 2" **/
function* gen() { yield [1, 2] }
for (const [x, y] of gen()) { console.log("x=", x, "y=", y) }

But after running it through Typescript it fails. Putting the above into the Typescript Playground illustrates the failure, namely that the for-of is converted to an array iteration loop but the generator is returning an object.

It seems Typescript is broken, and if so is this a known issue? I didn't see it on https://github.com/Microsoft/TypeScript.

What's the best workaround? Using Array.from on the generator function strikes me as the most coherent?

1 Answers

You are correct, the issue is that the for of loop is being transpiled to a simple array loop in es5/es3 target.

If you add "downlevelIteration": true to your tsconfig.json, it should work, and the resulting code will look completely different.

Do notice, that if you have other for of loops iterating over plain arrays, downlevel iteration will incur a small performance hit. (Which is why downlevel iteration is hidden behind a flag).

Also, I would read this, especially the part about 'Reducing Code Size with --importHelpers and tslib'.

Related