在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
相关产品推荐
相关产品推荐

