Last updated: Feb 29, 2024
Reading time·2 min
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.
Here are two examples of how the error occurs.
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); }
tsconfig.json
To solve the error, set the target
property to es6
in your
tsconfig.json file.
{ "compilerOptions": { "target": "es6", // ... your other options } }
The target option changes which JavaScript features are down-leveled and which are left intact.
If you use the String.matchAll
method and the error is still not resolved, add
ES2020.String
to your lib
array in 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.
{ "compilerOptions": { "target": "es5", "downlevelIteration": true, // ... your other options }, }
The downlevelIteration option transpiles your TypeScript code to an older version of JavaScript.
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
.
You can learn more about the related topics by checking out the following tutorials: