Type 'Number' cannot be used as an index type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 8, 2022

banner

Photo from Unsplash

Type 'Number' cannot be used as an index type in TypeScript #

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.

index.ts
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.

index.ts
// ✅ 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.

The error message means that you can't use the Number type when trying to index an array or object in TypeScript.
index.ts
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]
The examples above show how you can't use a value of type 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.

index.ts
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"

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.