简体   繁体   English

在打字稿中的类型声明期间在类内调用类

[英]Calling a class inside a class during type declaration in typescript

This is the structure of data that I need 这是我需要的数据结构

this.nodes=[
    {
      id: 1,
      name: 'root1',
      children: [
        { id: 2, name: 'child1' },
        { id: 3, name: 'child2' }
      ]
    },
    {
      id: 4,
      name: 'root2',
      children: [
        { id: 5, name: 'child2.1' },
        {
          id: 6,
          name: 'child2.2',
          children:[
            {id:7, name:'child2.2.1'}
          ]
        }
      ]
    },
  ];

For data type declaration I need to write a class which goes something like this 对于数据类型声明,我需要编写一个类似这样的类

export class EvaluationMapperNodes {
    id: number;
    name: string;
    children: EvaluationMapperNodes[];
}

Using EvaluationMapperNodes inside itself is giving error. 在自身内部使用EvaluationMapperNodes会出错。 but the depth of children is dynamic. 但是孩子的深度是动态的。 How do I recursively call class inside it. 如何在其中递归调用类。

PS Its Angular 2 project. PS其Angular 2项目。

Change your interface like : 像这样更改您的界面:

export class EvaluationMapperNodes {
  id: number;
  name: string;
  children?: EvaluationMapperNodes[];
}

The Error you must be getting because of this part 由于这部分您必须得到的错误

...
children: [
    { id: 5, name: 'child2.1' },
    {...

As it does not contain the children property, so it should be optional , and that you can achieve by using ? 由于它不包含children属性,因此它应该是optional ,并且可以使用?来实现? before property name like 在属性名称之前

children?: EvaluationMapperNodes[];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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