You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TypeScript中编写基础useQuery语句出现类型错误,原因是什么?

问题描述

我尝试在TypeScript中编写基础的useQuery语句获取数据,参考常规教程后写出如下代码:

import { useQuery } from '@tanstack/react-query'

const SomesComponent = () => {
  const someApi = useSomeApi()

  const fetchProducts = async () => {
    const response = await someApi.getAll()
    return response?.data
  }

  const { data } = useQuery('todos' /*<- error here */, () => fetchProducts())

  // ...
}

但在VSCode中出现了如下TypeScript错误:

No overload matches this call.
  Overload 1 of 3, '(options: UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.
      Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.
  Overload 2 of 3, '(options: DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): DefinedUseQueryResult<unknown, Error>', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.
      Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.
  Overload 3 of 3, '(options: UseQueryOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.

请问出现该错误的原因是什么?


错误原因及解决方案

这个错误是因为你使用的是TanStack React Query v4及以上版本,而参考的教程基于v3版本编写,两个版本的useQuery调用语法有重大差异:

  • React Query v3支持参数式调用:第一个参数为查询键(字符串/数组均可),第二个参数为查询函数
  • React Query v4+仅支持对象式调用:必须传入包含queryKey和queryFn属性的配置对象

修正后的代码示例:

import { useQuery } from '@tanstack/react-query'

const SomesComponent = () => {
  const someApi = useSomeApi()

  const fetchProducts = async () => {
    const response = await someApi.getAll()
    return response?.data
  }

  // 改为对象形式传入配置
  const { data } = useQuery({
    queryKey: ['todos'], // 推荐用数组形式的查询键,便于后续扩展参数
    queryFn: fetchProducts
  })

  // ...
}

额外说明:v4+强制使用对象参数是为了让API更清晰,避免参数顺序混淆,同时支持更多配置项的直观传递。若要保留v3语法,需降级到React Query v3版本,但不推荐——v4+包含更多性能优化与新特性。

内容的提问来源于stack exchange,提问作者Bersan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:11:20