首页 > 解决方案 > React TypeScript 如何遍历一个对象?

问题描述

这是特定于 React 的。

我有一个这样的对象:

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

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

我想在 React 组件中返回该对象的键值对,如下所示:

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

但是,我可以访问它们,key但不能访问它的值。我有这个错误:

TS:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“配置文件”。在“配置文件”类型上找不到具有“字符串”类型参数的索引签名。

我尝试使用Object.valuesfilter无法修复它。

标签: javascriptreactjstypescript

解决方案


尝试

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

推荐阅读