Type 'IterableIterator' is not an array type or string type

avatar

Borislav Hadzhiev

Tue Mar 22 20222 min read

banner

Photo by Grant Ritchie

Type 'IterableIterator' is not an array type or string type #

To solve the "Type 'IterableIterator' is not an array or a string type" error, set the target property to es6 in your tsconfig.json file or enable downlevelIteration to emit more compliant JavaScript code for iterations.

type iterableiterator is not array type

Here are two examples of how the error occurs.

index.ts
function* generator(a: number, b: number, c: number): IterableIterator<number> { yield a; yield b; yield c; } // ⛔️ Error: Type 'IterableIterator<number>' is not an array type // or a string type. Use compiler option '--downlevelIteration' // to allow iterating of iterators.ts(2569) for (const num of generator(5, 10, 15)) { console.log(num); // 👉️ 5, 10, 15 } // ------------------------------------------------------------------- const regexp = RegExp('he*', 'g'); const str = 'hello hey hi'; const matches = str.matchAll(regexp); // ⛔️ Error: Type 'IterableIterator<RegExpMatchArray>' is not // an array type or a string type. Use compiler option // '--downlevelIteration' to allow iterating of iterators.ts(2569) for (const match of matches) { console.log(match); }

To solve the error, set the target property to es6 in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "target": "es6", // ... your other options } }

The target option changes which JavaScript features are downleveled and which are left intact.

If this doesn't resolve the error, try restarting your IDE. VSCode often glitches and needs a reboot.

If you use the String.matchAll method and the error is still not resolved, add ES2020.String to your lib array in tsconfig.json.

tsconfig.json
{ "compilerOptions": { "target": "es6", "lib": [ "ES2020.String", // ... your other libs ], // ... your other options } }

ES6 is a good choice, because modern browsers support all ES6 features.

If you need to support older environments, you can use the downlevelIteration option to solve the error instead.

tsconfig.json
{ "compilerOptions": { "target": "es5", "downlevelIteration": true, // ... your other options }, }

The downlevelIteration option transpiles your TypeScript code to an older version of JavaScript.

This makes your code less performant and more verbose, however it is able to run in much older browsers.

ES6 added multiple iteration primitives, such as the for...of loop, array spread [...myArr1, ...myArr2], etc.

If you need to use these iteration primitives with target set to es5, you have to enable downlevelIteration in your tsconfig.json file.

Note that the emitted JavaScript is very verbose and less performant than if you leave the iteration primitives intact by setting target to es6.

Use the search field on my Home Page to filter through my more than 1,000 articles.