我有一个树结构TableOfContents:
export interface TableOfContents {
id: number;
title: string;
isExpanded: boolean;
children: TableOfContents[];
}我需要一个函数,用于搜索树数组中的项,并希望使其成为通用的。所以我做了下一个:
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);
你能帮我找个解决办法吗?
发布于 2020-12-27 15:14:03
在您的TreeNode.接口中,您的代码说children应该是实现TreeNode的任何东西的数组,而实际上您的意思是children应该是相同类型的TreeNode的数组。因此,使用this类型:
export interface TreeNode {
[key: string]: any;
children?: this[];
}发布于 2021-11-22 13:06:59
export type INode<T = any> = T & {
nodes: Array<INode<T>>;
}
const family: INode<{name?: string}> = {
name: 'Bogdan',
nodes: []
};https://stackoverflow.com/questions/65467090
复制相似问题