2

I've got following code snippet:

var iterator: IterableIterator<string> = iterBreadth(tree);
for(var item of iterator){
  log(item)
}

iterBreadth is just a generator function that returns an iterator. Iterators in TypeScript are of type IterableIterator<T> where T is a string in my case.

My question is - why is the playground yelling at me at the for..of iterator loop line:

enter image description here

?

How come iterators are limited to arrays and string only?


I've found at the official docs that, when targeting ES3 or ES5, only arrays are allowed in for..of loops. But that doesn't explain what are strings doing in the playground erorr message.


Besides, I can see that typescript is having hard time transpiling for..of. The following code seems to be transpiled against arrays precisely, since it's just iterating over indices (0, 1, 2), not calling next:

var iterator = iterBreadth(tree);
for (var _i = 0, iterator_1 = iterator; _i < iterator_1.length; _i++) {
    var item = iterator_1[_i];
    log(item);
}
2
  • You need to target es6 (or above) to be able to do that. But it seems that you know that already, so what exactly are you asking? Why targetting es6 is needed? Commented May 10, 2017 at 17:59
  • @NitzanTomer nope, the question is about the error message. Why does it indicate string type?! I find it misleading. Commented May 10, 2017 at 18:00

3 Answers 3

2

Typescript 2.3 added support for generators and the Iterator protocol for ES3 and ES5 targets. With new --downlevelIteration option, your example compiles without errors:

tsc --lib es6 --target es5 --downlevelIteration t.ts

--downlevelIteration option is not available in typescript playground however.

Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate over a string characters using the for/of loop:

const str = "str";
for (let char of str) {
    console.log(char);
}

Outputs:

s
t
r

That is the reason why the error message says string.

Comments

0

Nitzan's answer covers a good solution. If, for any reason, you need to handle your iterable as an array you can use Array.from()

var iterator: IterableIterator<string> = iterBreadth(tree);
for(var item of Array.from(iterator)){
    log(item)
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.