Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Liana Mikah
The "Type 'Number' cannot be used as an index type" TypeScript error occurs
when we use the Number
type instead of number
(lowercase n
). To solve the
error, make sure to only use the number
type with lowercase n
in your
TypeScript code.
Here is an example of how the error occurs.
const arr1: Number[] = [0, 1, 2]; // 👈️ capital N const arr2 = ['a', 'b', 'c']; // ⛔️ Type 'Number' cannot be used as an index type.ts(2538) arr2[arr1[0]];
We used the Number
, non-primitive object type to type the arr1
variable,
which caused the error.
To solve this, always use the number
type when typing numbers in TypeScript.
// ✅ now using number const arr1: number[] = [0, 1, 2]; const arr2 = ['a', 'b', 'c']; console.log(arr2[arr1[0]]); // 👉️ "a"
We used the primitive number type which resolved the error.
The error was caused because there is a difference between the primitive
number
, string
and boolean
types and the non-primitive Number
, String
,
Boolean
, Object
, etc.
The non-primitive types are objects and should never be used when typing values in TypeScript.
The
TypeScript best practices
documentation warns to never use the Number
, String
, Boolean
, Symbol
or
Object
non-primitive objects when typing values in your TypeScript code.
Instead, you should be using number
, string
, boolean
, symbol
and
Record
types.
Number
type when trying to index an array or object in TypeScript.const num: Number = 1; const arr = ['a', 'b', 'c']; // ⛔️ Error: Type 'Number' cannot be used as an index type.ts(2538) arr[num] const obj = { 0: 'a', 1: 'b', 2: 'c', }; const num2: Number = 2; // ⛔️ Error: Type 'Number' cannot be used as an index type.ts(2538) obj[num2]
Number
to access an array element at index or to access an object property.The solution is to use the number
type or let TypeScript infer the type if
declaring the value inline.
const num = 1; // 👈️ type is inferred const arr = ['a', 'b', 'c']; console.log(arr[num]); // 👉️ "b" const obj = { 0: 'a', 1: 'b', 2: 'c', }; const num2 = 2; // 👈️ type is inferred console.log(obj[num2]); // 👉️ "c"