将地图与打字稿一起使用时大对象的解构

destructuring of large objects when using map with typescript

我对 typeScript 还比较陌生,在我处理来自 GraphQL 端点的各种数据的项目中,我在注释方面遇到了很多困难。

稍后数据结构可能会发生变化,因此我使用 Apollo Client 为各种查询生成适当的 TypeScript 类型,以避免手动输入它们。这很好用:到目前为止一切顺利!

但是,当我想映射各种数据时,我遇到了困难:主要是当我使用 map() 函数并开始解构数据时,我很难找到有关如何执行此操作的示例?我不确定我是否 运行 陷入名称冲突?各种错误我不清楚。

示例:(这是一个较大代码块的片段 - 如果我将鼠标悬停在 seoDataObject 上,我可以看到它按预期正确注释 - 它是一个对象数组:

常量 seoDataObject: (AllUsersSeo_users_edges | null)[] |空 |未定义)


interface AllUsersSeo_users_edges {
  __typename: "RootQueryToUserConnectionEdge";
  /**
   * The item at the end of the edge
   */
  node: AllUsersSeo_users_edges_node | null;
}

const seo = seoDataObject?.map(({ node }) => node).find((node) => node.id === id)?.seo;

然后我收到以下错误:

var node: any
Property 'node' does not exist on type 'AllUsersSeo_users_edges | null'.ts(2339)

我如何使用 typescript 重写它?

'node' 确实存在于每个 seoDataObject 上 - 但在代码片段中 'node' 也是 map 函数中的一个参数,所以我根本无法理解如何在 Typescript 中正确执行此操作?

我不太明白你真正想问的是什么,你只是想通过 id 找到 seo,它可能在结果中,它可能是一个空值数组, 还是 null 本身?

那样的话const seo = seoDataObject?.filter(x => x.node).find(x => x.node.id === id)?.node.seo;