0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Apollo with TypeScript: Setup and Example

To use Apollo Client with TypeScript, install Apollo packages and GraphQL types, then create a typed Apollo client instance. Use generated TypeScript types for queries and mutations to ensure type safety in your GraphQL operations.
📐

Syntax

Here is the basic syntax to set up Apollo Client with TypeScript:

  • ApolloClient: Creates the client instance.
  • InMemoryCache: Caches query results.
  • gql: Parses GraphQL queries.
  • TypeScript types: Define or generate types for query results and variables.
typescript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://your-graphql-endpoint.com/graphql',
  cache: new InMemoryCache(),
});

// Define query with gql
const GET_DATA = gql`
  query GetData($id: ID!) {
    item(id: $id) {
      id
      name
    }
  }
`;

// TypeScript types for query variables and response
interface GetDataVars {
  id: string;
}

interface GetDataResponse {
  item: {
    id: string;
    name: string;
  } | null;
}
💻

Example

This example shows how to fetch data using Apollo Client with TypeScript types for safety.

typescript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/',
  cache: new InMemoryCache(),
});

const GET_COUNTRY = gql`
  query GetCountry($code: ID!) {
    country(code: $code) {
      code
      name
      capital
    }
  }
`;

interface GetCountryVars {
  code: string;
}

interface GetCountryResponse {
  country: {
    code: string;
    name: string;
    capital: string;
  } | null;
}

async function fetchCountry(code: string) {
  const { data } = await client.query<GetCountryResponse, GetCountryVars>({
    query: GET_COUNTRY,
    variables: { code },
  });
  return data.country;
}

fetchCountry('US').then(country => {
  if (country) {
    console.log(`Country: ${country.name}, Capital: ${country.capital}`);
  } else {
    console.log('Country not found');
  }
});
Output
Country: United States, Capital: Washington D.C.
⚠️

Common Pitfalls

Common mistakes when using Apollo with TypeScript include:

  • Not typing query variables and response data, which removes type safety.
  • Forgetting to install @types/graphql or Apollo dependencies.
  • Using incorrect generic types in client.query or useQuery hooks.
  • Not handling nullable fields properly in TypeScript interfaces.
typescript
/* Wrong: Missing types, no type safety */
client.query({
  query: GET_COUNTRY,
  variables: { code: 'US' },
}).then(result => {
  console.log(result.data.country?.name); // No type checking
});

/* Right: Use generics for type safety */
client.query<GetCountryResponse, GetCountryVars>({
  query: GET_COUNTRY,
  variables: { code: 'US' },
}).then(result => {
  console.log(result.data.country?.name); // Type checked
});
📊

Quick Reference

Tips for using Apollo with TypeScript:

  • Always define interfaces for query variables and response data.
  • Use Apollo Client generics to enforce types in queries and mutations.
  • Use tools like graphql-code-generator to auto-generate types from your schema.
  • Handle nullable fields carefully to avoid runtime errors.

Key Takeaways

Use TypeScript generics with Apollo Client methods to ensure type safety.
Define interfaces for your GraphQL query variables and response data.
Install all necessary Apollo and GraphQL type packages for smooth integration.
Consider using code generation tools to automate type creation from your schema.
Always handle nullable fields in your TypeScript types to prevent errors.