如何解决TanStack Infinite Query的重载匹配错误?
解决useInfiniteQuery TypeScript重载不匹配错误(TS2769)
问题背景
部署时调用useInfiniteQuery出现TypeScript重载不匹配错误(TS2769),错误提示getNextPageParam返回的string类型无法赋值给getInfinitePosts函数中定义为number类型的pageParam参数。
相关代码
useGetPosts函数
export const useGetPosts = () => { return useInfiniteQuery({ queryKey: [QUERY_KEYS.GET_INFINITE_POSTS], queryFn: getInfinitePosts, getNextPageParam: (lastPage) => { if (lastPage && lastPage.documents.length === 0) { return null; } const lastId = lastPage?.documents[lastPage?.documents.length - 1].$id; return lastId; }, }); };
分页函数getInfinitePosts
export async function getInfinitePosts({ pageParam }: { pageParam: number }) { const queries: any[] = [Query.orderDesc("$updatedAt"), Query.limit(10)]; if (pageParam) { queries.push(Query.cursorAfter(pageParam.toString())); } try { const posts = await databases.listDocuments( appwriteConfig.databaseId, appwriteConfig.postCollectionId, queries ); if (!posts) throw Error; return posts; } catch (error) { console.log(error); } }
组件使用代码
const { data: posts, fetchNextPage, hasNextPage } = useGetPosts();
错误信息
No overload matches this call. Overload 1 of 3, '(options: UndefinedInitialDataInfiniteOptions<DocumentList<Document> | undefined, Error, InfiniteData<DocumentList<Document> | undefined, unknown>, QUERY_KEYS[], number>, queryClient?: QueryClient | undefined): UseInfiniteQueryResult<...>', gave the following error. Type '(lastPage: DocumentList<Document> | undefined) => string | null | undefined' is not assignable to type 'GetNextPageParamFunction<number, DocumentList<Document> | undefined>'. Type 'string | null | undefined' is not assignable to type 'number | null | undefined'. Type 'string' is not assignable to type 'number'. ...
解决方案
问题核心是getNextPageParam返回的文档ID(字符串类型)与getInfinitePosts定义的pageParam(数字类型)不匹配,且实际代码中pageParam最终会被转为字符串传给Query.cursorAfter,因此调整类型定义即可解决:
- 修改
getInfinitePosts的pageParam类型为string | undefined(第一次加载无参数时为undefined) - 移除不必要的
toString()转换,直接使用字符串类型的pageParam
修改后的getInfinitePosts代码:
export async function getInfinitePosts({ pageParam }: { pageParam?: string }) { const queries: any[] = [Query.orderDesc("$updatedAt"), Query.limit(10)]; if (pageParam) { queries.push(Query.cursorAfter(pageParam)); } try { const posts = await databases.listDocuments( appwriteConfig.databaseId, appwriteConfig.postCollectionId, queries ); if (!posts) throw Error; return posts; } catch (error) { console.log(error); } }
此时TypeScript会自动推导useInfiniteQuery的参数类型,getNextPageParam返回的字符串类型与pageParam类型匹配,错误即可消除。
内容的提问来源于stack exchange,提问作者Yash Sharma
相关产品推荐
相关产品推荐

