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.
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.
}
Try using this union type with object
:
type TreeNode = {
children?: Array<TreeNode>;
} & object;
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 }
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.