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

如何解决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,因此调整类型定义即可解决:

  1. 修改getInfinitePosts的pageParam类型为string | undefined(第一次加载无参数时为undefined)
  2. 移除不必要的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:23:15