简体   繁体   中英

How to create an interface for object and array of objects in Angular 8 and type script?

I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

Sample API response like this

{
"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" },

    ]
}
}

在此处输入图片说明

what you have provided in this._erateColumn.next(columnList) method is columnList . And somehow columnList seems to be a single object of the interface ErateColumn, While your BehaviorSubject has type array of ErateColumn. Change that to ErateColumn or provide array in this._erateColumn.next(columnList) method for your code to work.

EDIT

According to the new screenshot of yours, it says property categories is missing so either make it optional like this

export interface ErateColumn {
  categories?:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

or provide categories.

May be this approach can help someone

You can convert JSON to typescript's class or interface , Using online tool json2ts or if you are using vs code (Visual Studio) use this extension QuickType - Paste JSON as Code

Note: Your JSON should be a valid JSON otherwise you will get errors

Hope this helps...

interface User {
   name: string;
   phone: string;
}

const user: User ==> Object

const usersList: User[] ===> Array of Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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