繁体   English   中英

如何在带有接口的 Typescript 中使用 React 中的对象数组?

[英]How can use an array of objects in React with Typescript with an interface?

我有一个对象数组,其中数据存储在 JSON 文件中。 JSON 文件如下所示:

[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden@xerex.com",
"nameList": [
  {
    "id": 0,
    "name": "Wendi Mooney"
  },
  {
    "id": 2,
    "name": "Holloway Whitehead"
    }
    ]
    },
    {
   "_id": "62bd5fbac3e5a4fca5e85e81",
   "index": 1,
   "nameList": [
  {
    "id": 0,
    "name": "Janine Barrett"
  },
  {
    "id": 1,
    "name": "Odonnell Savage"
  },
  {
    "id": 2,
    "name": "Patty Owen"
  }
]
},

之后我必须使用这个 object 作为另一个组件(someComponent)中的道具,我做了一个接口:

interface Props {
data: [
{
  _id: string;
  index: number;
  email: string;
  nameList: { id: number; name: string };
}
];
}

然而在那之后我得到了当前的错误:

Type '({ _id: string; index: number; nameList: { id: number; name: string; }[]; email?: undefined; } | { index: number; email: string; nameList: { id: number; name: string; }[]; _id?: undefined; } | { _id: string; index: number; email: string; nameList: ({ ...; } | ... 1 more ... | { ...; })[]; } | { ...; })[]' is not assignable to type '[{ _id: string; index: number; email: string; nameList: { id: number; name: string; }; }]'.
  Target requires 1 element(s) but source may have fewer.ts(2322)
someComponent.tsx(3, 3): The expected type comes from property 'data' which is declared here on type 'IntrinsicAttributes & Props'

可能是什么问题?

您在Props类型上指定了data ,但没有为输入数据 object 指定数据。

“数据”只是我存储数据的变量,所以我不会自己传递属性。 数据 = {数据}

data = {data} - 此处data应使用您的data类型Props指定。 如果您没有指定任何内容,typescript 将获取其属性并创建 object。 这就是您收到错误的原因。

Type '({ _id: string; index: number; nameList: { id: number; name: string; }[]; email?: undefined; } | { index: number; email: string; nameList: { id: number; name: string; }[]; _id?: undefined; } | { _id: string; index: number; email: string; nameList: ({ ...; } | ... 1 more ... | { ...; })[]; } | { ...; })[]' is not assignable to type '[{ _id: string; index: number; email: string; nameList: { id: number; name: string; }; }]'.

为您的输入数据提供类型或至少指定any类型以便解决错误。

检查这个TS 游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM