In my browser, the code works fine even without the typings. However, TypeScript is emitting an error stating that gen()
does not have a [Symbol.iterator]
method, which is required for it to be considered an Iterable
. I find this limitation odd because as far as I know, an Iterator
should be a valid object to use with a for...of
loop.
function *gen(): Iterator<number> {
yield 1
yield 2
yield 3
}
for (const val of gen()) {
console.log(val)
}
Could you please help me understand what mistake I am making here?
Edit: After removing the return type from the code above and allowing TypeScript to infer it automatically, I got IterableIterator
, which satisfied TypeScript. Does this mean I cannot simply use an Iterator
in a for...of
loop?