![](/img/trans.png)
[英]How do I specify an array of objects in Typescript using interface with specific attribute naming
[英]How do I specify an array with multiple objects in a TypeScript interface?
我有一些 React-Redux-Typescript 代码,我从 API 获得结果并尝试为响应对象创建接口。 这里我有我的示例数据:
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"
}
]
}
};
这是我的 object 接口:
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
}
]
}
我的减速器中出现以下错误:
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"
据我所知,问题是“特征”数组中有多个对象。 此特征数组中可能有多达十几个对象。 我该如何补救这个 typescript 错误?
您为feature
指定的类型是元组- 一个固定长度的数组,其元素具有已知类型。 以下是您想要的:
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[]
}
(注意:为了便于阅读,我已将“特征”提取到类型别名中,您不必这样做)
features -- Object 中的键值对具有与 Object 相同的 Array 类型,该类型具有键值对功能,值在 Array 内重复多次(无固定长度)- 这是指元组-- 一个 Z9327DAFFB399FZ04442818934F 功能帮助我们轻松声明相同的 Object 以检查任何类型、lint、编译错误
interface Feature {
"feature": string,
"value": string
}
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[]
}
//export 用于在我们导入文件的其他文件中声明接口时使用接口(主要用于model文件,而不是我们类的接口)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.