Reputation: 97
I am trying to read a JSON data : and i got this error Element implicitly has an 'any' type because expression of type 'string' can't be used to the index type my data is local josn file and I am importing them :
{
"user": {
"name": "foo",
"location": "India",
},
"product": {
"name": "Iphone",
"version": "12",
}
}
i am displaying like this
const data =data;
<div>
{Object.keys(data.user).map((key,i) => (
<p key={i}>
<span>{key}</span>
<span>{data.user[key]}</span>
</p>))}
</div>
every thing is working except for this line :
<span>{data.user[key]}</span>
it gives error :
Element implicitly has an 'any' type because expression of type 'string' can't be used to the index type
No index signature with a parameter of type 'string' was found on type
Upvotes: 1
Views: 1362
Reputation: 180
If you have an array of objects that contain strings, you can do what I did.
const rows: { [key: string]: string }[] = [
{
id: 'load-balancer-1',
name: 'Load Balancer 1',
rule: 'Round robin',
status: 'Starting',
other: 'Test',
example: '22',
},
...
];
Upvotes: 0
Reputation: 416
You could cast the keys to their keys in the object like so:
{(Object.keys(data.user) as (keyof typeof data.user)[]).map((key, i) => (
<p key={i}>
<span>{key}</span>
<span>{data.user[key]}</span>
</p>
))}
Upvotes: 2
Reputation: 6736
Define type
for data like below
const data: { [key: string]: { [key: string]: string } }
Working code - https://codesandbox.io/s/distracted-hopper-2vowh?file=/src/App.tsx:205-212
Upvotes: 0