Type ‘String’ cannot be used as an index type in Typescript

In this post, we will see how to fix error Type ‘String’ cannot be used as an index type in Typescript.

Type ‘String’ cannot be used as an index type in Typescript occurs when you use String(Starts with capital s) instead of string when trying to index array or object in Typescript.

Let’s see with the example:

Output

When you correct it to String to string, your error will be resolved.

Output

You got the error because there is difference in primitive number, string types and non primitive type Number, String.

As per typescript best practice docs, you should never use non primitive boxed objects Number, String, Boolean, Symbol, or Object as they are almost never used appropriately.

This error simply means you can’t use String type to index an array/object.

Let’s take another example:

When we used attr.name as index type for cntry1, we got error Type 'String' cannot be used as an index type because Attribute’s name is of type String(starts with capital S) rather than string.

To resolve the issue, use change String to string while declaring Attribute interface

Output:

Conclusion

To resolve the issue Type ‘String’ cannot be used as an index type in Typescript, change String(starts with capital S) to string while decaring data type.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *