首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现树的接口

如何实现树的接口
EN

Stack Overflow用户
提问于 2020-12-27 15:02:19
回答 2查看 379关注 0票数 1

我有一个树结构TableOfContents:

代码语言:javascript
复制
export interface TableOfContents {
  id: number;
  title: string;
  isExpanded: boolean;
  children: TableOfContents[];
}

我需要一个函数,用于搜索树数组中的项,并希望使其成为通用的。所以我做了下一个:

代码语言:javascript
复制
export interface TreeNode {
  [key: string]: any;
  children?: TreeNode[];
}

export interface TableOfContents extends TreeNode {
  id: number;
  title: string;
  isExpanded: boolean;
}

export const findInTrees = <TreeType extends TreeNode>(
  trees: TreeType[],
  callback: (el: TreeType) => boolean
): TreeType | null => {
  const tree = trees.find(tree => callback(tree));
  if (tree) {
    return tree;
  }
  for (const tree of trees) {
    if (tree.children) {
      const result = findInTrees(tree.children, callback);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

但是在行TS2345: Argument of type 'TreeNode[]' is not assignable to parameter of type 'TreeType[]'.上有一个错误const result = findInTrees(tree.children, callback);

你能帮我找个解决办法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-27 15:14:03

在您的TreeNode.接口中,您的代码说children应该是实现TreeNode的任何东西的数组,而实际上您的意思是children应该是相同类型的TreeNode的数组。因此,使用this类型:

代码语言:javascript
复制
export interface TreeNode {
  [key: string]: any;
  children?: this[];
}
票数 4
EN

Stack Overflow用户

发布于 2021-11-22 13:06:59

代码语言:javascript
复制
export type INode<T = any> = T & {
    nodes: Array<INode<T>>;
}



const family: INode<{name?: string}> = {
    name: 'Bogdan',
    nodes: []
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65467090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档