Property 'setLink' is missing in type 'ApolloClient<NormalizedCacheObject>' but required in type 'ApolloClient<any>

Viewed 8372

I am setting up a new typescript project with react and apollo client. I am attempting to wire in the client like so:

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'http://localhost:3000/graphql',
    headers: {
      authorization: localStorage.getItem('token'),
    },
  }),
});

function App() {
  return (
    <ApolloProvider client={client}>
      <div className="App">
       ...content goes here
      </div>
    </ApolloProvider>
    );
}

However, this throws an error during runtime:

TypeScript error in /src/App.tsx(60,21):
Property 'setLink' is missing in type 'ApolloClient<NormalizedCacheObject>' but required in type 'ApolloClient<any>'.  TS2741

    58 | function App() {
    59 |   return (
  > 60 |     <ApolloProvider client={client}>
       |                     ^
    61 |       <div className="App">

As this appears to be a type based problem, I attempted to be explicit when creating the Apollo client per the example here: https://github.com/apollographql/apollo-client/issues/2503

const client = new ApolloClient<NormalizedCacheObject>{ ...

But no dice. I'm not sure why I have dueling types compared to working examples. Help?

4 Answers

The @apollo/client package contains the imports from previously decoupled libraries like apollo-client and apollo-cache-inmemory.

If your imports look like this:

import { ApolloClient } from 'apollo-client'
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory'

Switch to this:

import {
  ApolloClient,
  InMemoryCache,
  NormalizedCacheObject,
} from '@apollo/client'

Solved the same error modifying the interface ApolloProviderProps by adding an union type(|) DefaultClient to the client property in the file ApolloProvider.d.ts

import React from 'react';
import { ApolloClient } from '../../core';
export interface ApolloProviderProps<TCache> {
    client: ApolloClient<TCache> | DefaultClient<TCache>;
    children: React.ReactNode | React.ReactNode[] | null;
}
export declare const ApolloProvider: React.FC<ApolloProviderProps<any>>;

This solves my issue.

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

const client = new ApolloClient({
  uri: 'your_graphql_endpoint',
  cache: new InMemoryCache(),
});

Non of the answers here, github issue #3639 and github issue #7309 worked for me.

I was using apollo-boost, @apollo/react-hooks.

I migrated to Apollo Client 3.0, Notes from docs:

The Apollo Boost project is now retired, because Apollo Client 3.0 provides a similarly straightforward setup.

With Apollo Client 3.0, the apollo-client package is retired in favor of @apollo/client. As part of migrating, remove all apollo-client dependencies.

Links:

Migrating

Setting up @apollo/client 3.0

Related