【问题标题】:Self Referencing Typescript Class自引用打字稿类
【发布时间】:2016-03-07 15:52:35
【问题描述】:

我有一个 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": []
         }
        }]
  }
}

当我在 typescript 中创建 taxon 模型时,我陷入了如何在 taxons 数组中表示自引用 taxon 的问题上。 我目前有这样的课程。

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

我如何获得对self 的引用,以便我可以拥有类似的东西

public taxons: Array<self>

或者我还能怎么做才能获得预期的行为。

【问题讨论】:

    标签: angularjs typescript angular self-reference


    【解决方案1】:

    我建议通过这样的界面执行此操作:

    interface IFoo {
        id: number;
        name: string;
        foos?: IFoo[];
    }
    
    var foo: IFoo = {
        id: 1,
        name: 'name 1',
        foos: [
            {id: 2, name: 'child 2'}
        ]
    }
    

    关键是使用? 使foos 属性可选

    【讨论】:

      【解决方案2】:

      如果你真的需要,你也可以使用一个类。 您所要做的就是指定类型。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-20
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 2018-08-06
        • 2021-07-02
        相关资源
        最近更新 更多