DEPRECATED IN FAVOR https://github.com/dotansimha/graphql-typed-document-node and included TypedQueryDocumentNode in graphql-js
yarn add graphql-tag-ts
or
npm install graphql-tag-ts
This project is basically strongly typed graphql-tag using Module augmentation.
Just installing this package you will be able to inject the types in your query declarations, no need to declaring them elsewhere or having to declare them when calling your queries.
queries file
import gql, { DocumentNode } from "graphql-tag-ts";
import gql_two from "graphql-tag";
/**
* You can import either version, this library
* is only doing module augmentation
* but using graphql-tag-ts is a safe bet
*/
export const query_one = gql<
{ hello: { world: string } },
{ variable: string }
>`
query($variable: String!) {
hello {
world
}
}
`;
/**
* You also can cast the DocumentNode type to the object.
* This method is better if you don't want to lose
* GraphQL query highlighting in your editor
*/
export const query_two: DocumentNode<
{ hello: { world: string } },
{ variable: string }
> = gql`
query($variable: String!) {
hello {
world
}
}
`;
application
import { useQuery } from "@apollo/react-hooks";
import { query_one } from "./queries";
export default () => {
// "data" is strongly typed!
// data = { hello: { world: string } } | undefined
const { data, loading } = useQuery(query_one, {
// "variables" is strongly typed too!
// variables = { variable: string } | undefined
variables: {
variable: "HelloWorld!"
}
});
return <div>{loading ? "Loading..." : data?.hello.world ?? "Not found"}</div>;
};
The module augmentation needs to be specified for every function that is required, so as is right now we are augmenting:
From @apollo/react-hooks
- useQuery
- useMutation
- useLazyQuery
- useSubscription
From apollo-server-integration-testing
- query
- mutate
If you want another library / function to be added please feel free to request it in the issues or send a pull request.
Usage with babel-plugin-graphql-tag
To use babel-plugin-graphql-tag (highly recommended) all you need to specify is the importName configuration option in your babel configuration.
.babelrc
{
...
"plugins": [
...
["babel-plugin-graphql-tag", { "importName": "graphql-tag-ts" }]
]
}