8

In TypeScript, I have an array that I am using like a map to access another array of objects. Here is an extremely simplified example of my code:

var mp : Number[] = [1, 2, 0];
var arr : any[] = ['a', 4, /regex/];

console.log(arr[mp[2]])

However, running this yields:

error TS2538: Type 'Number' cannot be used as an index type.

I've looked elsewhere but the other answers for this type of error don't pertain to something as simple as an array and a Number. If not a Number object, how can I index an array?

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
Riolku
  • 572
  • 1
  • 4
  • 10

1 Answers1

20

TypeScript has two basic number types, the primite number and the Object type Number. Refer to TypeScript: Difference between primitive types for an explanation, but in short:

JavaScript has the notion of primitive types (number, string, etc) and object types (Number, String, etc, which are manifest at runtime). TypeScript types number and Number refer to them, respectively.

In fact, if you run:

console.log(typeof 1);

You will notice that it returns number, not Number.

If you change your map to be an array of number objects, your code will compile without errors.

Riolku
  • 572
  • 1
  • 4
  • 10
  • 2
    `typeof(1)` is not necessary, just `typeof 1` is most commonly used. It's unnecessary parentheses making it look like a function call, just like typing `return(1)` – Ruan Mendes Jun 15 '21 at 13:55
  • Thanks, removed the parantheses – Riolku Jun 15 '21 at 14:21
  • 4
    "*TypeScript has two number types, the primite number and the Object type Number.*" there is also [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) – VLAZ Jun 15 '21 at 14:21
  • 2
    changed to "basic number types" – Riolku Jun 15 '21 at 14:22