Search code examples
typescriptapolloapollo-client

How to provide the TCache type when creating a new instance of ApolloClient?


I have the following code:

const client: ApolloClient<any> = new ApolloClient({
  uri: MY_URI,
});

And I'd like to replace any with a TCache type, as indicated by the VSCode tooltip that pops up when I remove any:

VSCode Tooltip

The issue is that TCache cannot be imported from apollo-client:

import { TCache } from "apollo-client"; // does NOT work

I also cloned their repo and tried to find a definition for TCache, but there's none.


Solution

  • Typically you would provide a cache option to the client and then provide the "cache shape" for that type. You can see this by looking at the types for ApolloClient:

    export declare type ApolloClientOptions<TCacheShape> = {
        …
        cache: ApolloCache<TCacheShape>;
        …
    };
    

    For the built-in InMemoryCache, looking at the code yields its shape is NormalizedCacheObject:

    export declare class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
        …
    }
    

    So your code would become:

    import { ApolloClient, InMemoryCache, NormalizedCacheObject} from "@apollo/client";
    
    const client: ApolloClient<NormalizedCacheObject> = new ApolloClient({
      cache: new InMemoryCache(),
      uri: MY_URI,
    });