Create better types from GraphQL response

Viewed 37

I am using GraphQL and have a big problem with the types. I like to make a request and save the result to a React state. There I would like to have a nice type. But I don't want to say const [animals, setAnimals] = useState<AnimalsListQueryResponse>(), because I should call my animals later as animals.edges[number].node.name. I would prefer to have something like animals.name.

To get the type I already find out that I could write: const [animals, setAnimals] = useState<AnimalsListQueryResponse['animals']['edges']>() But because the that can be an array or null, I cannot go deeper. How could I solve it and get just the "right" Animal Type?

export type AnimalsListQueryResponse = {
readonly animals: {
    readonly edges: ReadonlyArray<{
        readonly node: {
            readonly id: string;
            readonly name: string;
            readonly age: number | null;
        };
    } | null> | null;
    readonly pageInfo: {
        readonly hasNextPage: boolean;
        readonly hasPreviousPage: boolean;
        readonly endCursor: string | null;
        readonly startCursor: string | null;
    };
    readonly totalCount: number;
};

};

1 Answers

If you want to extract the inner type of a single node, you can do something like NonNullable<AnimalsListQueryResponse['animals']['edges']>[0]

Note that your state indicates an array, not a single element.

And as mentioned in prev comments, use GraphQL Code Generator. You will be amazed what this tool can do for you.

Related