8
votes

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

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

for(var index in myArray)
    console.log(myArray[index]) 

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?

3

3 Answers

9
votes

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);
});
2
votes

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

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