Type Object must have a Symbol.iterator method that returns an iterator

avatar

Borislav Hadzhiev

Last updated: Mar 9, 2022

banner

Photo from Unsplash

Type Object must have a Symbol.iterator method that returns an iterator #

The error "Type Object must have a Symbol.iterator method that returns an iterator" occurs when we try to use the spread syntax (...) to unpack an object in an array. To solve the error, wrap your object in an array or correct your typings.

Here is an example of how the error occurs.

index.ts
const obj = { name: 'James' }; // ⛔️ Error: Type Object must have a '[Symbol.iterator]()' // method that returns an iterator.ts(2488) const result = [...obj];

We tried to use the spread syntax to unpack the properties of an object directly into an array.

The solution for this depends on your use case. If you want to unpack the object into an array, wrap it in an array before using the spread syntax (...).

index.ts
const obj = { name: 'James' }; const result = [...[obj]]; console.log(result); // 👉️ [{name: 'James'}]

If you want to merge the properties of multiple objects, use the spread syntax with an object wrapper instead.

index.ts
const obj = { name: 'James' }; const result = { ...obj, ...{ age: 30 } }; console.log(result); // 👉️ {name: 'James', age: 30}

If you are trying to unpack an array of objects into another array, your typings might be wrong. For example, you could be typing an array of objects as an object.

Here is how you would type an object and an array of objects.

index.ts
type Person = { name: string; age: number }; type ArrayOfPeople = Person[];

Here is a more visual representation of the error.

index.ts
// ⛔️ Error: Type '{}' must have a '[Symbol.iterator]()' // method that returns an iterator.ts(2488) console.log([...{}]);

If your use case is to merge multiple arrays of objects into another array, you should be doing this.

index.ts
const arr1 = [{ name: 'James' }]; const arr2 = [{ name: 'Alice' }]; const result = [...arr1, ...arr2]; // 👇️ [{name: 'James'}, {name: 'Alice'}] console.log(result);

Now we can safely unpack the elements of the two arrays of objects into the result array.

Conclusion #

The error "Type Object must have a Symbol.iterator method that returns an iterator" occurs when we try to use the spread syntax (...) to unpack an object in an array. To solve the error, wrap your object in an array or correct your typings.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.