This error can occur in TypeScript due to various reasons.
To fix the error in TypeScript, it’s important to first understand the error itself, and to do that, you need to have a good understanding of the spread operator.
Understanding Spread Operator
The spread operator is denoted by three dots (…) and it allows you to spread the contents of an array, object into another array or object.
For example, suppose you have an array of numbers [1, 2, 3], you can use the spread operator to create a new array that contains all the elements of the first array, plus additional elements :
const numbers = [1, 2, 3, 4];
const newArray = [...numbers, 5, 6, 7, 8];
console.log(newNumbers); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
The spread operator always returns a copy of the elements, either you are using it in an array or in an object.
Similarly, you can use the spread operator in objects :
const student = { name: 'praveen', age: 20 };
const address = { country: 'India', state: 'Uttarakhand' };
const info = { ...student, ...address };
console.log(info);
// Output: {name: 'praveen', age: 20, country: 'India', state: 'Uttarakhand' }
Can we spread an array into a variable ?
let’s try to spread an array into a variable :
const array = [1, 2, 3, 4, 5];
const variable = ...array; // its wrong
const variable = 1, 2, 3, 4, 5 // a variable can store only one value
A variable can store only one value either it’s an object or an array or a string and so on. You can not store more than one value in a variable. If you do so you will get an error.
Can we spread an object into an array ?
You can not spread an object into an array directly.
The error “Type ‘Object’ must have a ‘[Symbol.iterator]()’ method that returns an iterator” occurs when we try to spread the object into an array.
Here is an example of how the error occurs :
const student = { name: 'praveen', age: 20 };
// ⛔️ Error: Type Object must have a '[Symbol.iterator]()'
// method that returns an iterator.ts(2488)
const result = [...student];
In above example we used the spread operator to take the properties of an object and put them directly into an array.
To resolve the error you need to wrap your object in an array.
If you put the spread object inside an array, the browser will treat it like an array of objects. However, if you don’t put the spread object inside an array, the browser will treat it like a regular array, which means you won’t be able to store data using named keys.
const student = { name: 'praveen', age: 20 };
const result = [...[student]];
console.log(result); //Output: [{ name: 'praveen', age: 20 }];
Summary
You can’t simply spread the object directly. Instead, you need to wrap the object in an array and then spread that array into another array. This was explain in the above example.