1

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
1
  • Seems there is no error. I've tried it in Codesanbox. Commented Nov 20, 2020 at 10:40

4 Answers 4

2

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>
))}
Sign up to request clarification or add additional context in comments.

Comments

0

Just cast key to type any:

<span>{data.user[key as any]}</span>

Comments

0

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

Comments

0

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',
    },
    ...
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.