Search code examples
angularjstypescriptangularself-reference

Self Referencing Typescript Class


I have a JSON object that i would like to represent in an angular2 typescript class. The JSON object has in it an array of objects of it's own type. The JSON object looks like this:

{ 
  "data": {
     "id": 5
     "type": "taxons",
     "attributes": {
       name: "Vehicles & Vehicle Accessories",
       "taxons": [{
         "id": 8,
         "type": "taxons",
         "attributes": {
            name: "Make",
            "taxons": []
         },
         "id": 9,
         "type": "taxons",
         "attributes": {
            name: "Model",
           "taxons": []
         }
        }]
  }
}

When I create the taxon model in typescript, I'm getting stuck on how to represent the self referencing taxon in the taxons array. I currently have the class like this.

export class Taxon {
  constructor (
    public id: number,
    public name: string,
    public taxons: //I am stuck here.
    )
}

How do I get reference to the self so that i can have something like

public taxons: Array<self>

Or how else can I do this to get the expected behavior.


Solution

  • You can also use a class if you really need to. All you have to do is specify the type.

    export class Taxon {
      constructor (
        public id: number,
        public name: string,
        public taxons: Taxon[]
        )
    }