107

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

2 Answers 2

229

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
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Is there a reason this is not by default?
@Ben I remember reading in some GitHub issue that the team was not particularly happy about the fact that the generated code is UGLY and does not really fit in with the TS design goal of generating readable JS ..
irony! The old school for (let i = 0; i < arr.length; i++) is every bit readable than any (of these showoff) for-of arrays :)
If you work with VSC, just restart it for the changes to take place
@Kariamoss yes, sometimes unfortunately restating is needed. "The Restart ts server" command is also a good option to restart just the ts language service
|
-11
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.

1 Comment

If adding the downlevelIteration parameter to your tsconfig.json file did not solve the problem, something is wrong. Perhaps you modified the wrong tsconfig.json file? Or perhaps the parameter was overridden in an inheriting tsconfig?

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.