Optimus Pette
Optimus Pette

Reputation: 3400

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.

Upvotes: 1

Views: 2237

Answers (2)

toskv
toskv

Reputation: 31600

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[]
    )
}

Upvotes: 0

Brocco
Brocco

Reputation: 64853

I would suggest doing this via an interface like so:

interface IFoo {
    id: number;
    name: string;
    foos?: IFoo[];
}

var foo: IFoo = {
    id: 1,
    name: 'name 1',
    foos: [
        {id: 2, name: 'child 2'}
    ]
}

The key is to make the foos property optional by using the ?

Upvotes: 3

Related Questions