简体   繁体   English

Typescript 接口树形结构

[英]Typescript interface for tree structure

I want to define an interface for tree structure.我想为树结构定义一个接口。

Each node can have zero or more children:每个节点可以有零个或多个子节点:

export interface TreeNode {
  children?: Array<TreeNode>;
}

I have implemented a traversing function for TreeNode s.我已经为TreeNode实现了遍历 function 。

export function traverseTree(treeData: Array<TreeNode> | TreeNode, callback: (treeNode: any) => any) {
  // implementation omitted
}

I want to test it.我想测试一下。 Code is as follows:代码如下:

const treeData = [
  {
    name: "root_1",
    children: [
      {
        name: "child_1",
        children: [
          {
            name: "grandchild_1"
          },
          {
            name: "grandchild_2"
          }
        ]
      }
    ]
  },
  {
    name: "root_2",
    children: []
  }
];
const traversingHistory = [];
const callback = (treeNode: any) => {
  traversingHistory.push(treeNode.name);
}
traverseTree(treeData, callback);

However, compilation fails because treeData 's argument of type cannot be applied to traverseTree .但是,编译失败,因为treeData的类型参数不能应用于traverseTree

I don't want to add attribute name to interface TreeNode because a tree node can have dynamic properties.我不想向接口TreeNode添加属性name ,因为树节点可以具有动态属性。 How can I modify TreeNode interface to accept more general types?如何修改TreeNode接口以接受更通用的类型?

The error you are probably getting is:您可能遇到的错误是:

Object literal may only specify known properties, and 'name' does not exist in type Object 文字只能指定已知属性,并且类型中不存在“名称”

If you want to allow other keys, it's got to be part of the type.如果你想允许其他键,它必须是类型的一部分。 You can do this with an index signature:您可以使用索引签名执行此操作:

export interface TreeNode {
  [key: string]: any // type for unknown keys.
  children?: TreeNode[] // type for a known property.
}

Try using this union type with object :尝试将此联合类型与object一起使用:

type TreeNode = {
    children?: Array<TreeNode>;
} & object;

I guess that using a generic instead [key: string]: any fits better:我猜想使用generic而不是[key: string]: any更适合:

export type Tree<T> = T & {
  children?: T[];
}

keeping the required and optional fields of the Item type we want to build a tree: Tree<Item> for this question, the Item is: { name: string } .保留我们要构建树的Item类型的必填和可选字段: Tree<Item>对于这个问题,Item 是: { name: string }

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

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