Typescript. How to avoid this error in foreach loop: "left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type"?
index
is a string. for..in
iterates over the keys of an object. It just so happens that the keys of an array are numerical. Still, they're stored as strings.
Check this out:
var myArray = [1, 2, 3];
for (var index in myArray) {
console.log(typeof index);
}
It's also worth noting that there's no guarantees about the order that you'll get those keys. Usually they'll appear in the right order but it would not be invalid for you to get "3", "1", "2"
, for example.
Instead, just use a normal for
loop. Then your indices will be numbers and you'll know for sure that you're moving through the array in order.
var myArray = [1, 2, 3];
for (var i = 0; i < myArray.length; i++) {
console.log(typeof i, myArray[i]);
}
You could also run through it using forEach
.
var myArray = [1, 2, 3];
myArray.forEach(function(val, index) {
console.log(typeof index, val);
});
It is a string, you can call parseInt(index, 10)
on it. That's because indices of objects are always strings, even on arrays, array just has some extra behavior to deal with keys that look like integers
However, note that that way of iterating over the array is error prone. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Note: for...in should not be used to iterate over an Array where the index order is important.
There's no guarantee that the elements will be iterated in order
You could always cast the element to avoid the error
console.log(index as number * 2); /
Considering your 'index' will be a number, it's possible you could suppress the warning / error via casting the index as a Number type
for(var index in myArray)
console.log(Number(index) * 2);
Alternatively
for(var index in myArray)
console.log(parseInt(index) * 2);