我有节点项目的平面列表。每个项目都有id
和parentId
。但是我想要一个函数,它返回每个相关(祖先)项目+“选定”项目本身的数组。
我编写了键入所有内容的函数。函数效果很好,但 TypeScript 仍然抱怨
Type '(items: Items, id: number) => any[]' is missing the following properties from type 'Item[]': pop, push, concat, join, and 24 more.
我不明白这个问题。整个解决方案如下。现场编辑。| 打字稿游乐场
interface Item {
id: number;
parentId: number | null;
}
type Items = Item[];
const exampleItems: Items = [
// Root element
{ id: 1, parentId: null },
// Children of 1
{ id: 2, parentId: 1 },
{ id: 3, parentId: 1 },
{ id: 4, parentId: 1 },
// Children of 3
{ id: 5, parentId: 3 },
{ id: 6, parentId: 3 }
];
const getRelated: Items = (items: Items, id: number) => {
const item = items.find(item => item.id === id);
if (item) {
const parentId = item.parentId;
if (parentId) {
return [item, ...getRelated(items, parentId)];
}
return [item];
}
return [];
};