typescript 如何定义无限嵌套的对象数组类型?
“`javascript
const array = [
{
name: ‘a’,
children: [
{
name: ‘aa’,
children: [
{
name: ‘aaa’,
children: []
}
]
},
{
name: ‘ab’,
children: []
},
]
},
{
name: ‘b’,
children: [
{
name: ‘ba’,
children: []
},
{
name: ‘bb’,
children: []
},
]
},
]
“`
我希望定义一个函数来展平这个多维嵌套的对象数组,把它变成这样:
“`javascript
[
{name: ‘a’, children: []},
{name: ‘aa’, children: []},
{name: ‘aaa’, children: []},
{name: ‘ab’, children: []},
{name: ‘b’, children: []},
{name: ‘ba’, children: []},
{name: ‘bb’, children: []},
]
“`
我的函数是这样写的:
“`javascript
function flat(array, children = ‘children’) {
const res = []
const recursive = (target) => {
target.map(item => {
res.push(item)
if(item.hasOwnProperty(children) && item[children].length) {
recursive(item[children])
}
})
}
recursive(array)
return res
}
“`
到目前为止,需求是可以实现的。但是当我想用 typescript 来实现的时候,我发现我不知道该如何定义 array 的类型了。万 v 友,求帮助啊
发现 V2EX 对 markdown 代码块语法支持的不太好,贴个[有道云笔记地址]( http://note.youdao.com/noteshare?id=b80252fbd7248f58dc14446823ff90a1&sub=2839057A8A83481C9AE6D1632E63F819)