TanStack Query V5中pageParam类型不存在的TypeScript报错求助
解决TanStack Query V5中无限查询queryFn的pageParam类型错误
问题分析
你在TanStack Query V5中实现无限查询时遇到TS2339错误,提示pageParam不存在于{ queryKey: QueryKey; signal: AbortSignal; meta: Record<string, unknown> | undefined; }类型上。这是因为V5对类型系统做了明确区分:
- V4中通用
QueryFunction会自动兼容无限查询参数,但V5将通用查询与无限查询的函数类型拆分开 - 你当前给
queryFn指定的是通用QueryFunction类型,该类型参数不包含pageParam,只有无限查询专用的InfiniteQueryFunction才会携带这个参数
修复方案
方案1:移除queryFn的显式类型声明(推荐)
由于你的函数最终返回UseInfiniteQueryOptions,TypeScript会自动推导queryFn的正确类型,无需手动指定。修改后的代码:
const queryFn = ({pageParam}) => notificationControllerGetNotification({cursor: pageParam, ...params}, axiosOptions);
方案2:显式使用InfiniteQueryFunction类型
如果需要保留类型声明,需替换为无限查询专用类型,并指定正确泛型参数:
import { InfiniteQueryFunction } from '@tanstack/react-query'; // ... const queryFn: InfiniteQueryFunction< Awaited<ReturnType<typeof notificationControllerGetNotification>>, unknown // 根据你的cursor实际类型替换,比如string | number > = ({pageParam}) => notificationControllerGetNotification({cursor: pageParam, ...params}, axiosOptions);
额外优化:给pageParam指定具体类型
如果你的cursor是特定类型(比如字符串),可以进一步明确类型提升安全性:
const queryFn: InfiniteQueryFunction< Awaited<ReturnType<typeof notificationControllerGetNotification>>, string // 假设cursor为字符串类型 > = ({pageParam = ''}) => // 添加默认值处理首次加载场景 notificationControllerGetNotification({cursor: pageParam, ...params}, axiosOptions);
验证修复
修改后TypeScript会正确识别pageParam的存在,错误将消失。同时建议检查getNotificationControllerGetNotificationQueryKey函数是否适配V5类型规范,避免后续出现其他类型问题。
内容的提问来源于stack exchange,提问作者Arseniy
相关产品推荐
相关产品推荐

