Apollo With TypeScript

Origin

Start with a simple React Component wrapped with the graphql higher order component from React Apollo.

The above code pulls some data from a GraphQL API using a query and includes lifecycle information, such as loading and error information.

With a few minor changes, we can tell TypeScript how to support us in writing code within this render function.

• We need to tell TS what the shape of our data from our graphql server will look like. We manually write the types for our response data.
• The last line is where the magic happens. We tell TS what the shape of the result will look like from the server when the graphql enhancer wraps a component.

If you already had your project set up with TS, and have already typed your response data, all you have to do is add the type to the graphql HOC and you are off!

Wrapped components are almost always exported and used by a component somewhere else in your tree, so if your exported component has prop requirements, we need to tell TS so it can help prevent errors elsewhere in our tree. Since the graphql wrapper suppors polymorphic types, we can use the second type parameter of it to do just that.