Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript and Iterator: Type 'IterableIterator<T>' is not an array type

Tags:

typescript

When I use the yield* expression on TypeScript, it always gets an error.

Type 'IterableIterator' is not an array type.

How can I set the types correctly without using any to avoid the errors?

function* g1(): IterableIterator<number> {
  yield 2;
  yield 3;
  yield 4;
}

function* g2(): IterableIterator<number> {
  yield 1;
  // ERROR: Type 'IterableIterator<number>' is not an array type.
  yield* g1();
  yield 5;
}

const iterator = g2();
like image 458
kechol Avatar asked Mar 11 '18 09:03

kechol


People also ask

What is IterableIterator?

It's explained in detail here: " IterableIterator is an interface defined by TypeScript that combines the contracts of Iterables and Iterator into one. This is because, in some cases, it makes sense to have the Iterable as an Iterator itself, removing the need to have an external class that serves as the iterator."

How do I iterate through a list in TypeScript?

To iterate over array of objects in TypeScript, we can use the for-of loop. to loop through the products array. product is the object being iterated through, so we can get the productDesc property from the object.

What is an iterator in JavaScript?

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value. The next value in the iteration sequence. done.


1 Answers

If possible update target to es2015 (or above) in the tsconfig to resolve the error without enabling down level iteration`:

{
  "compilerOptions": {
    "target": "es2015"
  }
}

If you target es5, enable downLevelIteration explicitly in the tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "downlevelIteration": true
  }
}
like image 150
Titian Cernicova-Dragomir Avatar answered Oct 29 '22 03:10

Titian Cernicova-Dragomir