【问题标题】:Problem with typescript while making request to SWR向 SWR 发出请求时出现打字稿问题
【发布时间】:2021-01-19 18:55:21
【问题描述】:

我想知道传递给我下面函数的参数的类型是什么

const fetcher = async (...args) => {                                
~_  0   const res = await fetch(...args);                                                                       
    1                                            
~   2   return res.json();                                                                                      
    3 };  

这是我的 SWR 提取器函数,这是我遇到的错误

[tsserver 2556] [E] Expected 1-2 arguments, but got 0 or more.

SWR 钩子

const { error, data } = useSWR(`/api/albums/list/${user.id}`, fetcher)

【问题讨论】:

    标签: javascript reactjs typescript next.js swr


    【解决方案1】:

    这是fetch函数的TypeScript签名:

    declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
    

    如果你使用函数rest parameters...args,你的fetcher函数可以像这样用零参数调用,tsc不会报错。

    fetcher();
    

    或者,很多参数(比如四个参数):

    fetcher("localhost", {}, {}, {});
    

    然后,您使用spread syntax 调用fetch API。 spread的参数不满足fetch的函数签名(参数不能为0或大于2),所以tsc报错。

    所以你最好这样修改:

    const fetcher = async (
      input: RequestInfo,
      init: RequestInit,
      ...args: any[]
    ) => {
      const res = await fetch(input, init);
      return res.json();
    };
    

    包版本:"typescript": "^4.1.3"

    【讨论】:

    • 既然除了前两个参数之外你没有做任何额外的参数,那么完全放弃...args不是更好吗?
    • @SimonW 是的,我不确定fetcher 是否需要其他参数。所以我保留...args
    • 嗨,你有一个如何使用它的例子吗?我很想知道,我应该如何调用 fetcher,将它的 init 对象及其值传递给它。示例:const {data, error} = useSWR("/some/path", fetcher("some/path", {headers: {}})) 正确的方法是什么?
    猜你喜欢
    • 2019-08-08
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-08-12
    • 2020-09-09
    • 2021-09-06
    相关资源
    最近更新 更多