0

I have very simple typescript code, just to iterate over an array of numbers:

const myTable = {};

// data is typed to 'number[]'
const data = [1,2,3,4,5,6,7,8,9,10];

// item is typed to 'string'
for(const item in data) {
    // compiler error due to item is string type
    myTable[item%2] = true;
}

Why typescript type item to string instead of number when it knows data is number[]?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • `item` is not an item from the array. It's a *key*. And keys are always strings (or symbols). `for...in` iterates over the keys of the object, `for...of` iterates over the values of array. – VLAZ May 11 '22 at 08:18
  • when you say key do you mean index? I get confused by the terms now. – user842225 May 11 '22 at 08:22
  • mytable will not accept number as it's key, – Shahriar Shojib May 11 '22 at 08:22
  • @user842225 Arrays are objects, so indexes of arrays are still just object keys. – VLAZ May 11 '22 at 08:24
  • I see. Thanks for the comments. I am fine either close this or someone makes an answer I will accept. – user842225 May 11 '22 at 08:39
  • BTW, `if...in` is referring to value right? – user842225 May 11 '22 at 08:42
  • What do you mean by `if...in`? There is no such language construct in JS/TS, `for...in` is an actual thing like `for (const x in obj)`. If you mean `if (x in obj)` that's the [`in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) which will return a boolean of whether or not `x` exists as a key in `obj` or up its prototype chain. – VLAZ May 11 '22 at 08:57
  • I mean `if(value in hashtable)`, sorry that I was thinking not array. – user842225 May 11 '22 at 09:37

0 Answers0