0

I am using graphql-codegen to generate Typescript typings for my React project. With graphql, you can set up queries to return only the properties that you need. This is useful but also results in pretty complex looking object types for my Typescript definition file. I have a Query that returns several nested items. I was wondering if it would be possible to extract the typings of just the tags property?

How would I use Typescript to extract the following type:

tags?: Maybe<Array<Maybe<(
        { __typename?: 'Tag' }
        & Pick<Tag, 'id' | 'name'>
      )>>>

From this base object type (I've indicated the part of the type I'd like to extract):

type ManageTeamPageQuery = (
    { __typename?: 'Query' }
    & { authedTeam?: Maybe<(
      { __typename?: 'Team' }
      & Pick<Team, 'id' | 'name' | 'imageEnding' | 'facebookPixelId' | 'subscriptionId'>
      & { domains?: Maybe<Array<Maybe<(
        { __typename?: 'Domain' }
        & Pick<Domain, 'id' | 'name'>
      )>>>, tags?: Maybe<Array<Maybe<( <--------- HERE
        { __typename?: 'Tag' } <----------------- HERE
        & Pick<Tag, 'id' | 'name'> <------------- HERE
      )>>> }
    )> }
);

What's tricky for me is that the nested properties can be null or undefined, so I am not sure how to deeply access them?

Please note that graphql-codegen defines Maybe as:

export type Maybe<T> = T | null;

For reference, the type generated from ManageTeamPageQuery results from a graphql that looks like:

query ManageTeamPage($id: Int!) {
    authedTeam(id: $id) {
        id
        name
        imageEnding
        facebookPixelId
        subscriptionId
        domains {
            id
            name
        }
        tags {
            id
            name
        }
    }
}
Jordan Lewallen
  • 1,681
  • 19
  • 54
  • Please consider modifying the code in this question so as to constitute a [mcve] which, when dropped into a standalone IDE like [The TypeScript Playground (this is a link to your code in a web IDE)](https://tsplay.dev/mZadDN), clearly demonstrates the issue you are facing (with no typos, unrelated errors, or undeclared types or values). This will allow those who want to help you to immediately get to work solving the problem without first needing to re-create it. And it will make it so that any answer you get is testable against a well-defined use case. – jcalz Sep 09 '21 at 03:56
  • It's possible you're looking `type Tags = NonNullable["tags"]>` as in [this code](https://tsplay.dev/Nd4XMN), but I'd love to see a [mcve] here that would play nicely enough with a standalone IDE. Also I guess it depends on what you mean by "extract" the type here, and since `tags?: Maybe<...` is not a valid type I'm not sure if you want `Tags` to have the key `tags` in it or not. If you could make explicit what you're looking for in terms on input and output, it would help. Good luck! – jcalz Sep 09 '21 at 04:02

0 Answers0