My goal is to create a simple function within a class that generates an Apollo Client. Below is the code I have implemented:
import appConfig from 'config/app-config';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import LocalStorageKeys from 'constants/local-storage-keys';
import { setContext } from '@apollo/client/link/context';
export class ApolloClientServiceImpl {
private cache: InMemoryCache;
constructor() {
this.cache = new InMemoryCache();
}
createApolloClient(idToken: string): unknown {
const httpLink = createHttpLink({
uri: appConfig.hasura.url,
});
const authLink = setContext((_, { headers }) => {
let bearerToken = localStorage.getItem(LocalStorageKeys.TOKEN);
if (idToken) {
bearerToken = idToken;
}
return {
headers: {
...headers,
authorization: bearerToken ? `Bearer ${bearerToken}` : '',
},
};
});
return new ApolloClient({
link: authLink.concat(httpLink),
cache: this.cache,
});
}
}
The issue arises with the return type of the createApolloClient
function. If I specify it as
ApolloClient<InMemoryCache>
and use the following return statement:
return new ApolloClient<InMemoryCache>({
link: authLink.concat(httpLink),
cache: this.cache,
});
This results in the error:
Type 'InMemoryCache' is not assignable to type 'ApolloCache<InMemoryCache>'.
Types of property 'restore' are incompatible.
Type '(data: NormalizedCacheObject) => InMemoryCache' is not assignable to type '(serializedState: InMemoryCache) => ApolloCache<InMemoryCache>'.
Types of parameters 'data' and 'serializedState' are incompatible.
Type 'InMemoryCache' is not assignable to type 'NormalizedCacheObject'.
Index signature is missing in type 'InMemoryCache'.ts(2322)
Given the limited documentation on this topic in the Apollo client docs, my question is, what is the correct return type for this function?
EDIT: By sticking with just:
return new ApolloClient({
link: authLink.concat(httpLink),
cache: this.cache,
});
And changing the return type to
ApolloClient<NormalizedCacheObject>
, this resolves the error. Many thanks to Alluan Hadad.