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:
1 2 3 4 5 6 7 8 9 |
const country = { name: 'China', }; const countryName : String = 'name'; console.log(country[countryName]); |
Output
When you correct it to String
to string
, your error will be resolved.
1 2 3 4 5 6 7 8 9 |
const country = { name: 'China', }; const countryName : string = 'name'; console.log(country[countryName]); |
Output
1 2 3 |
China |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
interface Attribute { name: String; } interface Country { name: string; } const cntry1: Country = { name: 'India', }; const attr: Attribute = { name: 'name', }; console.log(cntry1[attr.name]); |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
interface Attribute { name: string; } interface Country { name: string; } const cntry1: Country = { name: 'India', }; const attr: Attribute = { name: 'name', }; console.log(cntry1[attr.name]); |
Output:
1 2 3 |
India |
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.