[英]How to create an interface for object and array of objects in Angular 8 and type script?
我正在尝试为对象、对象和对象数组创建一个接口。
示例界面
export interface ErateColumn {
categories:{
[key:string]:column[]
}
}
interface column {
label:string
value:string
}
像这样的示例 API 响应
{
"categories": {
"Basic Information": [
{ label: "Applicant Type", value: "ApplicantType" },
{ label: "Organization Name", value: "OrganizationName" },
],
"FRN Lineitem": [
{ label: "Monthly_Cost", value: "Monthly_Cost" },
],
"FRN status": [
{ label: "Purpose Type", value: "PurposeType" },
]
}
}
您在this._erateColumn.next(columnList)
方法中提供的是columnList
。 不知何故, columnList
似乎是接口 ErateColumn 的单个对象,而您的 BehaviorSubject 具有 ErateColumn 类型数组。 将其更改为 ErateColumn 或在this._erateColumn.next(columnList)
方法中提供数组以使您的代码工作。
编辑
根据您的新屏幕截图,它说缺少属性categories
,因此可以像这样将其设为可选
export interface ErateColumn {
categories?:{
[key:string]:column[]
}
}
interface column {
label:string
value:string
}
或提供类别。
可能这种方法可以帮助某人
您可以将JSON转换为 typescript 的类或接口,使用在线工具json2ts或者如果您使用的是vs 代码(Visual Studio),请使用此扩展QuickType - Paste JSON as Code
注意:你的 JSON 应该是一个有效的 JSON 否则你会得到错误
希望这可以帮助...
interface User {
name: string;
phone: string;
}
const user: User ==> Object
const usersList: User[] ===> Array of Objects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.