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?

Related Posts

  • 21 May

    How to Clear Array in TypeScript

    Table of ContentsBy setting array’s length to 0Using splice() methodBy reassigning the variableUsing pop() methodWas this post helpful? In this post, we will see how to clear array in Typescript. There are multiple ways to do it. Let’s go through them. By setting array’s length to 0 To clear array in TypeScript: Set length of […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.