最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React TypeScript how to iterate through an object? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 19, 2020 at 17:55 VietViet 6,95315 gold badges46 silver badges79 bronze badges 2
  • 2 Does this answer your question? Element implicitly has an 'any' type because expression of type 'string' can't be used to index – ecrb Commented Apr 19, 2020 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 Commented Apr 19, 2020 at 18:11
Add a comment  | 

3 Answers 3

Reset to default 9

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>
  )
}

What about using Object.entries combined with a map method, like this:

Object.entries(NewPerson).map(([key, value]) => {
   <div>{key}: {value}</div>
})

I had the same problem and resolved it like this:

Object.entries(NewPerson).map(([key, value]) => {
 <div>{key}: {value}</div>
})
发布评论

评论列表(0)

  1. 暂无评论