简体   繁体   中英

Typescript: How can I refer to an anonymous type that is a child of a named type?

I am using apollo-codegen to generate TypeScript types from the GraphQL queries embedded in the tsx files in my project. An example of a generated type is:

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

I would be passing the "nodes" to a helper method that renders a React component for each node. I'd like to do something like:

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

}

Is there a way to achieve what I want? Does what I want even make sense?

You can use the bracket notation

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

Although in your case I'd just edit the type (You generate it only once for starting out, I hope?)

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
}

Then just MooNode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM