reactjs - 如何在 TypeScript 接口(interface)中指定具有多个对象的数组?

标签 reactjs typescript redux

我有一些 React-Redux-Typescript 代码,我正在从 API 获取结果并尝试为响应对象创建接口(interface)。这里有我的示例数据:

    const exampleState: ExampleState = {
  loading: false,
  products: {
    "id": 11001,
    "campus": "hrnyc",
    "name": "Camo Onesie",
    "slogan": "Blend in to your crowd",
    "description": "The So Fatigues will wake you up and fit you in. This high energy camo will have you blending in to even the wildest surroundings.",
    "category": "Jackets",
    "default_price": "140.00",
    "created_at": "2021-01-12T21:17:59.200Z",
    "updated_at": "2021-01-12T21:17:59.200Z",
    "features": [
        {
            "feature": "Fabric",
            "value": "Canvas"
        },
        {
            "feature": "Buttons",
            "value": "Brass"
        }
    ]
  }
};

这是我的该对象的界面:

export interface Featured {
  "id": number
  "campus": string,
  "name": string,
  "slogan": string,
  "description": string,
  "category": string,
  "default_price": string,
  "created_at": string,
  "updated_at": string,
  "features": [
      {
          "feature": string,
          "value": string
      }
  ]
}

我的 reducer 中出现以下错误:

TypeScript error in /Users/theo/Desktop/hrnyc34-fec-falcullele/my-app/src/reducers/singleProductReducer.ts(20,5):
Type '[{ feature: string; value: string; }, { feature: string; value: string; }]' is not assignable to type '[{ feature: string; value: string; }]'.
  Types of property 'length' are incompatible.
    Type '2' is not assignable to type '1'.  TS2322

    18 |     "created_at": "2021-01-12T21:17:59.200Z",
    19 |     "updated_at": "2021-01-12T21:17:59.200Z",
  > 20 |     "features": [
       |     ^
    21 |         {
    22 |             "feature": "Fabric",
    23 |             "value": "Canvas"

据我所知,问题是“features”数组中有多个对象。此特征数组中最多可能有十几个对象。我该如何纠正这个 typescript 错误?

最佳答案

您为feature指定的类型是tuple - 其元素具有已知类型的固定长度数组。以下是您想要的:

type FeatureType = {
   "feature": string,
   "value": string
}

export interface Featured {
  "id": number
  "campus": string,
  "name": string,
  "slogan": string,
  "description": string,
  "category": string,
  "default_price": string,
  "created_at": string,
  "updated_at": string,
  "features": FeatureType[]
}

(注意:为了可读性,我已将“feature”提取到类型别名中,但您不必这样做)

关于reactjs - 如何在 TypeScript 接口(interface)中指定具有多个对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65754846/

相关文章:

javascript - 在 react-hook 中使用回调进行多次调度?

reactjs - React.js URL 更改但 View 未更改

javascript - 将嵌套的 else if 语句转换为 JavaScript 中的 switch 语句

javascript - 稍后在 TypeScript 中解决或拒绝 Promise

javascript - react 查询:如果出现错误,请勿按时间间隔重新获取

javascript - 为什么 React Router 是一个 React 组件?

jquery - 使用 Typescript 和 RequireJS 导入 jqueryui

javascript - 从 Redux 状态属性渲染 React 组件

javascript - 更新 Redux 存储后,我的组件不会重新呈现

javascript - 如何在 ReactJS + Redux 中检查数组中的每个对象?