Using Apollo with TypeScript
As your application grows, you may find it helpful to include a type system to assist in development. Apollo supports type definitions for TypeScript out of the box. Both apollo-client and React Apollo ship with definitions in their npm associated packages, so installation should be done for you after the libraries are included in your project.
The most common need when using type systems with GraphQL is to type the results of an operation. Given that a GraphQL server's schema is strongly typed, we can even generate TypeScript definitions automatically using a tool like apollo-codegen.
Typing hooks
React Apollo's useQuery, useMutation and useSubscription hooks are fully typed, and Generics can be used to type both incoming operation variables and GraphQL result data, as we will be illustrating:
useQuery
useMutation
useSubscription
Typing Render Prop Components
Using Apollo together with TypeScript couldn't be easier than using it with component API released in React Apollo 2.1:
Now the <Query /> component render prop function arguments are typed. Since we are not mapping any props coming into our component, nor are we rewriting the props passed down, we only need to provide the shape of our data and the variables for full typing to work! Everything else is handled by React Apollo's robust type definitions.
This approach is the exact same for the <Query/>, <Mutation/>,and <Subcription /> components! Learn it once, and get the best types ever with Apollo.
Extending components
In previous versions of React Apollo, render prop components (Query, Mutation and Subscription) could be extended to add additional type information:
Since all class based render prop components have been converted to functional components, extending components in this manner is no longer possible. While we recommend switching over to use the new useQuery, useMutation and useSubscription hooks as soon as possible, if you're looking for a stop gap you can consider replacing your class with a wrapped and typed component:
Typing Higher Order Components
Since the result of a query will be sent to the wrapped component as props, we want to be able to tell our type system the shape of those props. Here is an example setting types for an operation using the graphql higher order component :
Previous:
Interacting with cached data
Next:
Testing React components
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics