如何缩小useSWRInfinite的getKey返回类型以解构数组键?
解决useSWRInfinite中getKey返回数组的TypeScript类型错误
问题根源是默认的SWRInfiniteKeyLoader返回类型过于宽泛(包含字符串、数组、对象等),TypeScript无法确定你返回的是数组,导致fetcher中解构数组时出现类型错误。可以通过明确getKey的返回类型或给useSWRInfinite指定泛型约束来解决。
步骤1:定义明确的类型约束
先给分页数据和键类型定义具体的TypeScript接口:
// 定义你的数据项类型 interface Item { id: string; // 根据实际id类型调整,比如number } // 定义分页返回数据的结构 interface PageData { items: Item[]; } // 定义getKey返回的数组键类型 type InfiniteItemKey = ["Items", string];
步骤2:修改getKey函数,明确返回类型
不要直接使用SWRInfiniteKeyLoader类型,而是给getKey的参数和返回值指定具体类型,同时处理第一页page为null的情况:
const getKey = (pageNum: number, page: PageData | null): InfiniteItemKey | null => { // 第一页无历史数据,返回初始请求键 if (pageNum === 0) { return ["Items", ""]; // 对应初始请求的startingAfter为空 } // 处理无更多数据的情况 if (!page?.items.length) { return null; // 返回null会终止后续分页请求 } const lastItem = page.items[page.items.length - 1]; return ["Items", lastItem.id]; };
步骤3:给useSWRInfinite指定泛型
通过泛型明确响应数据、错误和键的类型,让TypeScript正确推断fetcher的参数类型:
import useSWRInfinite from "swr/infinite"; // 假设你的接口返回数据结构是PageData,可根据实际调整 const resp = useSWRInfinite<PageData, Error, InfiniteItemKey>( getKey, ([_, lastItemId]) => fetch("/items", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ startingAfter: lastItemId }) }).then(res => res.json()) );
这样修改后,TypeScript就能确定fetcher的参数是InfiniteItemKey类型的数组,解构操作不会再出现类型错误。
内容的提问来源于stack exchange,提问作者onlyanegg
相关产品推荐
相关产品推荐

