【问题标题】:Typescript: How can I refer to an anonymous type that is a child of a named type?Typescript:如何引用作为命名类型的子级的匿名类型?
【发布时间】:2018-01-14 17:20:51
【问题描述】:

我正在使用apollo-codegen 从嵌入在我项目的 tsx 文件中的 GraphQL 查询生成 TypeScript 类型。生成类型的示例是:

export type MooQuery = {
  wines:  {
    edges:  Array< {
      node:  {
        nodeId: string,
        wineName: string | null,
        wineryId: number | null,
        vintageId: number | null,
        uomId: number | null
      },
    } | null > | null,
  } | null,
};

我会将“节点”传递给一个辅助方法,该方法为每个节点呈现一个 React 组件。我想做类似的事情:

renderHelper(node: MooQuery.wines.edges.node) { // this won't work

}

有没有办法实现我想要的?我想要的还有意义吗?

【问题讨论】:

    标签: typescript graphql apollo


    【解决方案1】:

    您可以使用括号表示法

    renderHelper(node: MooQuery['wines']['edges'][0]['node']) { // this should work
      //                                         ^^^ Don't forget the 0 for the array
    }
    

    虽然在你的情况下我只是编辑类型(你只生成一次以开始,我希望?)

    export type MooQuery = {
      wines:  {
        edges:  Array<{node: MooNode} | null > | null,
      } | null,
    };
    
    export type MooNode = {
        nodeId: string,
        wineName: string | null,
        wineryId: number | null,
        vintageId: number | null,
        uomId: number | null
    }
    

    那就MooNode

    【讨论】:

    • 这看起来很棒,谢谢!但我收到一个非常奇怪的错误:error TS2339: Property 'edges' does not exist on type '{ edges: ({ node: { nodeId: string; wineName: string | null; wineryId: number | null; vintageId: ...'. - 对我来说看起来很矛盾?!
    • 我无法重现。我建议你打开一个新问题并链接到这个问题。
    猜你喜欢
    • 2018-09-04
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2021-04-27
    • 2013-05-23
    • 1970-01-01
    相关资源
    最近更新 更多