How to automatically derive result types for gql queries?

Right now, when I define a query with gql``, I also always have to define the return type by myself or else I don’t get any useful typechecking for the results of useQuery and useMutation.

Here is an example:

const CreateWorkspace = gql`
  mutation CreateWorkspace($name: String!) { 
    createWorkspace(name: $name) { id name }

interface CreateWorkspaceData {
  createWorkspace: { id: string, name: string }

// somewhere else
const [createWorkspace] = useMutation<CreateWorkspaceData>(CreateWorkspace)

Instead of writing interface CreateWorkspaceData by hand, can I somehow derive CreateWorkspaceData from CreateWorkspace automatically?

Definitely! Check out graphql-code-generator. As long as you have access to your schema you can generate the types you’re looking for automatically.

1 Like