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

时间:2020-03-31 16:45:05

标签: typescript apollo react-apollo react-apollo-hooks

我正在尝试向useMutation明确提供客户。一切正常,除了打字稿似乎出现类型不匹配的事实。

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

客户端与阿波罗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似乎期望被推断出的另一种类型。我该如何解决这种不匹配?

1 个答案:

答案 0 :(得分:1)

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

export const client = new ApolloClient<InMemoryCache>({

我试图了解如何使用此参数,但我不太清楚。老实说,空对象似乎也可以正常工作:

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

但是当读取源代码时,它看起来像想要缓存类型。