2016-03-07 21 views
0

我有一个JSON对象,我想在angular2 typescript类中表示。 JSON对象中有它自己类型的对象数组。 JSON对象是这样的:自引用类型脚本类

{ 
    "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": [] 
     } 
     }] 
    } 
} 

当我创建打字稿中taxon模型,我陷入了如何代表自己的taxons数组中引用taxon。 我目前有这样的班级。

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

如何获得参考self,这样我可以有类似

public taxons: Array<self> 

还是怎么回事,我能做到这一点,以获得预期的行为。

回答

0

你也可以使用一个类,如果你真的需要。 您只需指定类型即可。

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

我会建议通过接口像这样的:

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

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

的关键是使foos酒店可随意使用?