React TypeScript how to iterate through an object?

Issue

This is specific for React.

I have an object like this:

interface Profile {
    name: string;
    title: string;
}

const NewPerson: Profile = {
    name: "John Smith",
    title: "Software Engineer"
}

And I’d like to return the key – value pair of that object in a React component like so:

function MyFunc() {
  return (
   <div>
    {
      Object.keys(NewPerson).map((key) => (
        <div>{key}: {NewPerson[key]}</div>
      ))
     }
    </div>
  )
}

However, I can access they key but not its value. I have this error:

TS: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Profile’.
No index signature with a parameter of type ‘string’ was found on type ‘Profile’.

I’ve tried to use Object.values and filter but cannot fix it.

Solution

try

interface Profile {
    name: string;
    title: string;
    [key: string]: string;
}
const NewPerson: Profile = {
    name: "John Smith",
    title: "Software Engineer"
}
function MyFunc() {
  return (
   <div>
    {
      Object.keys(NewPerson).map((key: keyof Profile) => (
        <div>{key}: {NewPerson[key]}</div>
      ))
     }
    </div>
  )
}

Answered By – dellink

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published