TS 创建TreeNode类型

想要实现的效果如:创建一个区域类,包含区域名称 name,区域编码 code,子区域 children

interface Area {
    name : string,
    code : string,
    children : Array<Area>
}

这样的实现似乎已经很完美了,但是如果有多个tree类型,每一个都需要手动添加 children : Array<T> ,我是一个懒人 哈哈哈,那就进行如下修改


interface Area {
    name: string,
    code: string
}

type TreeNode<T> = {
    [P in keyof T]: T[P]
} & {
    children?: Array<TreeNode<T>>
}

这样既保证了原有的数据类型,又添加了children,那这样干有什么用吗?当然,我们可以依据 TreeNode 类型封装一些泛型函数如 :

let areaTree: TreeNode<Area> = {
    name: "01",
    code: "01",
    children: [
        {
            name: "0101",
            code: "0101",
        },
        {
            name: "0102",
            code: "0102",
            children: [
                {
                    name: "010201",
                    code: "010201",
                }
            ]
        }
    ]
}

function getLevelTreeNodes<T extends TreeNode<T>>(tree: T, level: number) {

    let ret = new Array<T>();

    function find(currentTree: T, currntLevel: number) {
        if (currntLevel === level) {
            ret.push(currentTree);
            return;
        }

        if (currentTree.children) {
            currentTree.children.forEach(child => {
                find(child, currntLevel + 1);
            })
        }
    }

    find(tree, 0);

    return ret;
}

let level = getLevelTreeNodes(areaTree, 2);

console.log(level); // [ { name: '010201', code: '010201' } ]

当然您也可以将常用的方法封装成一个类,集中处理 TreeNode 类型

posted @ 2022-11-12 12:22  辣椒鱼儿酱  阅读(307)  评论(0编辑  收藏  举报