Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of array index string or number?

Tags:

typescript

when I loop over the indexes of an array they show up as string. But indexing an array using strings is forbidden. Isn't that incoherent? Why is it so?

for (const i in ["a", "b", "c"]) {
  console.log(typeof i + " " i + " " + arr[i]);  // -> string 0 'a', etc.
}
arr['0'] // ERROR ts7105: Element implicitly has an 'any' type because index expression is not of type 'number':
like image 415
Johannes Schacht Avatar asked Feb 01 '26 19:02

Johannes Schacht


1 Answers

for ... in iterates over the keys of the given object.

An array will have its indices as keys, see Object.keys([4,5,1]) which prints ["0", "1", "2"]. To iterate a typed array use for ... of See the docs. If you need the index use a regular for(let i=0;i<arr.length;i++) or for(let [i,el] of arr.entries()) loop.

As for your question, yes it does seem incoherent, but it looks like indexing inside a loop using the loop variable allows string indices. But be aware that index + 1 will be "01" because the index is a string.

like image 60
Josef Avatar answered Feb 03 '26 10:02

Josef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!