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

Typescript

Typescript Problem Overview


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();

Typescript Solutions


Solution 1 - Typescript

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
  }
}

Solution 2 - Typescript

tsc demo.ts --lib "es6","dom" --downLevelIteration

Use this command for compilation. It will solve the issue. Adding these values in tsconfig.json will not solve the problem, if tsconfig.json is created with target:es5. updating tsconfig.json manually will not work. Use this command, just change the name of your .ts file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkecholView Question on Stackoverflow
Solution 1 - TypescriptTitian Cernicova-DragomirView Answer on Stackoverflow
Solution 2 - TypescriptDeepakView Answer on Stackoverflow