如何在打字稿中将数组与对象映射

时间:2020-10-16 20:45:18

标签: javascript reactjs typescript

嗨,我正在尝试填充通过界面制作的对象:

export interface MainInfo {
    speaks: Array<Object>
}

然后在组件中按如下所示填充它:

import { MainInfo } from '../../interfaces/Interface';

export const UserCard: React.FC = () => {
let mainInfo: MainInfo = {
    speaks:  [
      {
        "language": "Ukrainian",
        "level": "Native"
      },
      {
        "language": "Russian",
        "level": "Fluent"
      }
    ]
  }
return(
<>
 {mainInfo.speaks.map((speaksInfo, id) => {
     return (
        <div className="languages" key={id}>
           <p>{speaksInfo.language}</p>
           <p>{speaksInfo.level}</p>
        </div>
     );
 })}
</>
);
};

但是数组没有映射,我出错了

Property 'level' does not exist on type 'Object'.  TS2339
   <p>{speaksInfo.level}</p>
                  ^

如何解决此问题?

1 个答案:

答案 0 :(得分:3)

您可以尝试这样更好地键入MainInfo吗?

export interface MainInfo {
    speaks: {
        language: string;
        level: string;
    }[]
}