【问题标题】:Type 'DefaultClient<unknown>' is not assignable to type 'ApolloClient<object>'类型“DefaultClient<unknown>”不可分配给类型“ApolloClient<object>”
【发布时间】:2020-07-12 07:16:58
【问题描述】:

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

Type 'DefaultClient&lt;unknown&gt;' is not assignable to type 'ApolloClient&lt;object&gt;'.

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

【问题讨论】:

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


    【解决方案1】:

    看来您应该将InMemoryCache 作为类型参数:

    export const client = new ApolloClient<InMemoryCache>({
    

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

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

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

    【讨论】:

    • 似乎都不起作用。在这两种情况下,消息都不会消失。
    • 奇怪,我可以重现你的错误,当我使用这些类型时它就消失了。
    • 我一定做错了什么,它确实有效。我的坏
    猜你喜欢
    • 2020-07-28
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2017-04-10
    • 2020-11-23
    • 2020-01-10
    相关资源
    最近更新 更多