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

avatar

Borislav Hadzhiev

Last updated: Mar 8, 2022

banner

Photo from Unsplash

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

The "Type 'String' cannot be used as an index type" TypeScript error occurs when we use the String type instead of string (lowercase s). To solve the error, make sure to use the string type with lowercase s in your TypeScript code.

Here is an example of how the error occurs.

index.ts
const obj = { name: 'James Doe', } // 👇️ using String (capital S) const str: String = 'name'; // ⛔️ Error: Type 'String' cannot be // used as an index type.ts(2538) obj[str]

We used the String, non-primitive object type to type the str variable, which caused the error.

To solve this, always use the string type when typing strings in TypeScript.

index.ts
interface Employee { name: string; // 👈️ use string lowercase s } const obj: Employee = { name: 'James Doe', }; const str = 'name'; console.log(obj[str]); // 👉️ "James Doe"

We used the primitive string 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 String type when trying to index an object in TypeScript.

index.ts
interface Employee { key: String; } const obj1: Employee = { key: 'name', }; const obj2 = { name: 'James Doe', }; // ⛔️ Error: Type 'String' cannot be used as an index type.ts(2538) obj2[obj1.key]

The code snippet above shows how using the String non-primitive, object type causes an error, because it can't be used to index the object at a specific property.

To get around this, use the primitive string type.

index.ts
interface Employee { key: string; } const obj1: Employee = { key: 'name', }; const obj2 = { name: 'James Doe', }; // 👇️ "James Doe" console.log(obj2[obj1.key as keyof typeof obj2]);

Conclusion #

The "Type 'String' cannot be used as an index type" TypeScript error occurs when we use the String type instead of string (lowercase s). To solve the error, make sure to use the string type with lowercase s 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.