Daniel Santos Daniel Santos - 6 months ago 104
Javascript Question

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"?

this is a very common usage of javascript or typescript foreach:

myArray = ["a","b","c"]

for(var index in myArray)

the code logs: a b and c

However in typescript the "index" var is considered to be a string. .
When I make any calculations, for instance index*2, the TS compuler shows the fallowing compiler error:

for(var index in myArray)
console.log(index * 2); // TS compiler error.

Error TS2362 The left-hand side of an arithmetic operation must be of
type 'any', 'number' or an enum type

but logs 0,2 and 4 when executed (as expected)

How can I avoid or suppres this error?


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);