我有一些 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/