5

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.

Viet
  • 6,513
  • 12
  • 42
  • 74
  • 2
    Does this answer your question? [Element implicitly has an 'any' type because expression of type 'string' can't be used to index](https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b) – ecrb Apr 19 '20 at 18:03
  • No, I don't think so. I've been reading the answer there but assigning keyof typeof in my case isn't an option. I only have 1 interface and 1 object. – Viet Apr 19 '20 at 18:11

3 Answers3

8

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>
  )
}
dellink
  • 544
  • 3
  • 16
  • Thank you for your suggestion, but I got this error: ``` Argument of type '(key: "title" | "name") => JSX.Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'. Types of parameters 'key' and 'value' are incompatible. Type 'string' is not assignable to type '"title" | "name"' ``` – Viet Apr 19 '20 at 18:07
5

What about using Object.entries combined with a forEach loop, like this:

Object.entries(NewPerson).map(([key, value]) => {
   <div>{key}: {value}</div>
})
Ignacio Elias
  • 578
  • 4
  • 9
1

I had the same problem and resolved it like this:

Object.entries(NewPerson).map(([key, value]) => {
 <div>{key}: {value}</div>
})
David Buck
  • 3,752
  • 35
  • 31
  • 35