TS2488
Type '{ [month: number]: string; }' must have a 'Symbol.iterator' method that returns an iterator.
Broken Code ❌
const months: {
[month: number]: string;
} = {
1: 'January',
2: 'February',
};
for (const month of months) {
console.log(month);
}Fixed Code ✔️
The simplest way to loop over an object is to create an iterable object by using Object.entries.
Another method is to add a property called [Symbol.iterator] to your object. The value of this property has to return an iterator. Here you can learn how to create an iterator.
const months: {
[month: number]: string;
} = {
1: 'January',
2: 'February',
};
const entries = Object.entries(months);
for (const [key, value] of entries) {
console.log(key, value);
}