打字稿递归类型

时间:2020-10-28 13:22:36

标签: typescript

尽我所能地为递归数据结构创建类型。任何人都可以对应该做的事情做些改进吗?也就是说,如果我设置了当前的绒毛投诉:

const graph: INestedGraph<typeof data> = data; 

任何帮助将不胜感激!

interface INestedGraph<T> {
    name: string;
    position?: number[];
    children?: T[] extends INestedGraph<infer U>[] ? INestedGraph<U>[]: null[]; 
}
const data =  {
    name: "root",
    children: [
      {name: "child #1"},
      {name: "child #2",
        children: [
          {name: "grandchild #1",
            children: [{name: "great-grandChild#1"}]},
          {name: "grandchild #2"},
          {name: "grandchild #3"}
        ]
      }, 
      {name: 'child #3', 
        children: [
            {name: 'grandchild #6'}
        ]}
    ]
  }; 

1 个答案:

答案 0 :(得分:3)

你不能只是这样做吗?

interface INestedGraph {
    name: string;
    position?: number[];
    children?: INestedGraph[]
}