In my project, I have a structured TableOfContents system:
export interface TableOfContents {
id: number;
title: string;
isExpanded: boolean;
children: TableOfContents[];
}
To implement a search function for finding an item in an array of trees and make it generic, I made the following adjustments:
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;
};
However, I encountered an error
TS2345: Argument of type 'TreeNode[]' is not assignable to parameter of type 'TreeType[]'.
on the line const result = findInTrees(tree.children, callback);
I would appreciate your assistance in finding a solution to this issue.