将 useQuery 与 TypeScript 一起使用时出现“没有重载匹配此调用”错误

时间:2021-06-30 20:36:45

标签: reactjs typescript next.js react-query

我的打字稿有类型问题。

我有以下 API:

export const clientAPI ={
//...
  getOptions: async (myParam: number) =>
    get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) => {
      localStorage.setItem('result', JSON.stringify(result))
      return result
    }),
//...
}

假设 get 方法如下:

const get =
  <T>(url: string) =>
    () => {
      const token = localStorage.getItem('token')
      return fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
      }).then((res) => parseResponse<T>(res))
    }

我调用 getOptions 如下:

useQuery("result", clientAPIs.getOptions(value as number));

我需要的是将响应放入本地存储,以便通过动态选择访问它,这取决于少数事件。当我更改一个值时,我会调用一个动态返回选项的 API,所以这就是我需要将它们放在本地存储中的原因。 问题是我调用它的方式(上面的最后一段代码)给出了一些类型错误,即使它按照我的意愿编译并实际存储了响应。

错误如下:

No overload matches this call.
  Overload 1 of 3, '(queryKey: "result", options?: UseQueryOptions<unknown, unknown, unknown, "result"> | undefined): UseQueryResult<unknown, unknown>', gave the following error.
    Type 'Promise<Options[]>' has no properties in common with type 'UseQueryOptions<unknown, unknown, unknown, "result">'.
  Overload 2 of 3, '(queryKey: "result", queryFn: QueryFunction<unknown, "result">, options?: UseQueryOptions<unknown, unknown, unknown, "result"> | undefined): UseQueryResult<...>', gave the following error.
    Argument of type 'Promise<Options[]>' is not assignable to parameter of type 'QueryFunction<unknown, "result">'.
      Type 'Promise<Options[]>' provides no match for the signature '(context: QueryFunctionContext<"result", any>): unknown'.ts(2769)
(property) getOptions: (country: string) => Promise<Options[]>

这更像是警告,但我想知道如何解决。

2 个答案:

答案 0 :(得分:1)

您向 useQuery 调用传递了一个 promise(clientAPIs.getOptions(...) 返回了一个 promise),但它实际上需要一个函数作为 fetcher 参数。

要解决此问题,您只需将第二个参数修改为函数即可。

useQuery("result", () => clientAPIs.getOptions(value as number));

答案 1 :(得分:0)

那不是在 transition: all 0.5s 前多加一对括号吗?你已经在传递类型和 url,不知道后面那个括号

.then()