0

我有节点项目的平面列表。每个项目都有idparentId。但是我想要一个函数,它返回每个相关(祖先)项目+“选定”项目本身的数组。

我编写了键入所有内容的函数。函数效果很好,但 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 [];
};
4

1 回答 1

3

这不是你键入const函数的方式。您所写的内容转换为“我想要一个getRelated以 type命名的 const 变量Items”,然后将其分配一个函数作为值。这就是异常告诉你的。

你可能想要的是

const getRelated = (items: Items, id: number): Items => {

游乐场链接

于 2020-10-28T14:36:58.027 回答