【问题标题】:Narrow useSWRInfinite getKey return type缩小 useSWRInfinite getKey 返回类型
【发布时间】:2023-02-14 17:12:14
【问题描述】:

我在使用 useSWRInfinite 和返回数组的 getKey 函数时遇到问题。以下是一个简化的示例,我在 fetcher 函数的参数上遇到了这个打字稿错误。

Type 'string | [any, ...unknown[]] | readonly [any, ...unknown[]] | Record<any, any>' is not an array type.

有没有办法缩小 getKey 函数的返回类型,以便我可以解构数组键?

import useSWRInfinite, { SWRInfiniteKeyLoader } from "swr/infinite";

const getKey: SWRInfiniteKeyLoader = (pageNum, page) => {
  const lastItem = page.items[page.items.length - 1];

  return ["Items", lastItem.id];
};

const resp = useSWRInfinite(
  getKey, ([_, lastItemId]) => fetch('/items', {body: JSON.stringify({startingAfter: lastItemId})})
)

【问题讨论】:

    标签: typescript swr


    【解决方案1】:

    首先,params 作为单独的参数传递给 fetcher,而不是作为数组,所以你不需要解构它们!

    至于打字,SWRInfiniteKeyLoader在内部使用了any,因此您将无法使用此界面完全输入您的功能。但您可以手动输入,如下所示:

    // Adjust page type according to your data
    const getKey = (pageNum: number, page: { items: Array<{ id: number }> }) => {
      const lastItem = page.items[page.items.length - 1];
    
      // Use `as const` here
      return ['Items', lastItem.id] as const;
    };
    
    // ...
      
      // key is now string and lastItemId is number
      const resp = useSWRInfinite(getKey, (key, lastItemId) =>
        fetch('/items', { body: JSON.stringify({ startingAfter: lastItemId }) })
      );
    

    【讨论】:

    • 谢谢!传播论点解决了大部分问题。我还发现您可以键入 fetcher 函数,其中第二个类型参数是键类型。 const fetcher: Fetcher&lt;Item[], [string, string]&gt; = (key, lastItemId) =&gt; {}
    【解决方案2】:

    您可以向 SWRInfiniteKeyLoader 添加类型参数:

    const getKey: SWRInfiniteKeyLoader<YourResponseDataType, [string, string | undefined] | null> = (pageNum, page) => {
      const lastItem = page.items[page.items.length - 1];
    
      return ["Items", lastItem.id];
    };
    
    

    我使用 string|undefined 作为最后一个项目 ID,因为它对于第一页是未定义的。

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 2019-03-02
      • 1970-01-01
      • 2019-09-09
      • 2018-08-27
      • 2021-11-21
      • 2018-09-18
      • 2018-06-19
      相关资源
      最近更新 更多