Intern
Why is for...of highlighted in red in TypeScript, but a regular for is not?
sobes.tech AI
Answer from AI
If for...of is highlighted in red in TypeScript, but the regular for is not, it is most likely because the object you are trying to iterate over with for...of is not iterable.
for...of only works with iterable objects (arrays, strings, Map, Set, etc.). If the variable does not implement the Iterable interface, TypeScript will throw an error.
Example:
const obj = { a: 1, b: 2 };
for (const item of obj) { // Error: obj is not iterable
console.log(item);
}
for (let key in obj) { // Works, iterates over keys
console.log(key);
}
Unlike for...of, the regular for or for...in can work with objects by iterating over their properties.
To fix the error, ensure that you only use for...of with iterable objects.