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 TreeNodes.
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.
I don't want to add attribute name to interface TreeNode because a tree node can have dynamic properties. How can I modify TreeNode interface to accept more general types?
The error you are probably getting is:
Object literal may only specify known properties, and 'name' does not exist in type
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.
}
I guess that using a generic instead [key: string]: any fits better:
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 }.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With