使用 Lodash 和 TypeScript 将包含子项的数组展平
Flatten an array with children using Lodash and TypeScript
使用 TypeScript 代码,我试图展平对象数组,其中每个元素都可以包含子元素:
function getMenu (menus:Array<Menu>, name:string | undefined) {
console.log('getMenu', name, menus[0])
const test = _(menus)
.thru(function (coll) {
return _.union(coll, _.map(coll, 'children') || [])
})
console.log('getMenu 2', test)
return name
}
我有这个错误阻碍了我:
argument of type 'Menu[][]' is not assignable to parameter of type 'List'.
Index signatures are incompatible.
Type 'Menu[]' is missing the following properties from type 'Menu': label, icon, route, selectable, and 2 more.
注意:代码在 JavaScript 中运行良好。
_.map(coll, 'children')
returns 菜单[][]。我们应该将其展平以使其成为 Menu[].
试试下面的代码:
function getMenu(menus: Array<Menu>, name: string | undefined) {
console.log('getMenu', name, menus[0]);
const test = _(menus).thru(function(coll) {
const flattenData = flatten(_.map(coll, 'children')); // flattening the data here
return _.union(coll, flattenData);
});
return name;
}
使用 TypeScript 代码,我试图展平对象数组,其中每个元素都可以包含子元素:
function getMenu (menus:Array<Menu>, name:string | undefined) {
console.log('getMenu', name, menus[0])
const test = _(menus)
.thru(function (coll) {
return _.union(coll, _.map(coll, 'children') || [])
})
console.log('getMenu 2', test)
return name
}
我有这个错误阻碍了我:
argument of type 'Menu[][]' is not assignable to parameter of type 'List'.
Index signatures are incompatible.
Type 'Menu[]' is missing the following properties from type 'Menu': label, icon, route, selectable, and 2 more.
注意:代码在 JavaScript 中运行良好。
_.map(coll, 'children')
returns 菜单[][]。我们应该将其展平以使其成为 Menu[].
试试下面的代码:
function getMenu(menus: Array<Menu>, name: string | undefined) {
console.log('getMenu', name, menus[0]);
const test = _(menus).thru(function(coll) {
const flattenData = flatten(_.map(coll, 'children')); // flattening the data here
return _.union(coll, flattenData);
});
return name;
}