类型 'DefaultClient<unknown>' 不可分配给类型 'ApolloClient<object>'

Type 'DefaultClient<unknown>' is not assignable to type 'ApolloClient<object>'

我正在尝试向 useMutation 显式提供客户端。一切正常,除了 typescript 似乎发现类型不匹配这一事实。

Type 'DefaultClient<unknown>' is not assignable to type 'ApolloClient<object>'.

客户端与 apollo 中显示的客户端非常相似 token authentication documentation

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

我真正要做的就是导入客户端并将其作为 useMutation 的选项提供。

import {useMutation} from '@apollo/react-hooks'
import {client} from './client'

const MY_QUERY = `
  ...
`

const [myQuery] = useMutation(MY_QUERY, {
  client: client,
  onCompleted: () => {
    // do some stuff..
  }
})

useMutation 似乎期待推断出的另一种类型。我该如何解决这种不匹配?

您似乎应该将 InMemoryCache 作为类型参数:

export const client = new ApolloClient<InMemoryCache>({

我试图了解这个参数是如何使用的,但我不太明白。老实说,空对象似乎也能正常工作:

export const client = new ApolloClient<{}>({

但是在阅读源代码时,它看起来像是需要缓存类型。

InMemoryCache 扩展了 NormalizedCachedObject 形状。此形状用于以序列化形式表示 Apollo 缓存的一个实例。 https://www.apollographql.com/docs/react/api/cache/InMemoryCache/#extract.

export const client = new ApolloClient<NormalizedCachedObject>({})