The TypeScript exception "is not iterable" occurs when the value which is given as the right hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object.

What went wrong?

The value which is given as the right hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object.  

An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol.

How to iterate over Object properties

In TypeScript (like JavaScript), Objects are not iterable unless they implement the iterable protocol.

Therefore, you cannot use for…of to iterate over the properties of an object.


//Wrong way of iterating

var obj = { 'France': 'Paris', 'England': 'London' };
for (let p of obj) { // TypeError: obj is not iterable
    // …
}

Instead you have to use Object.keys or Object.entries, to iterate over the properties or entries of an object.


//CORRECT way of iterating

var obj = { 'France': 'Paris', 'England': 'London' };
// Iterate over the property names:
for (let country of Object.keys(obj)) {
    var capital = obj[country];
    console.log(country, capital);
}

for (const [country, capital] of Object.entries(obj))
    console.log(country, capital);

For more visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/is_not_iterable

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *