最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problem with typescript while making request to SWR - Stack Overflow

programmeradmin0浏览0评论

I want to know what is the type of this args that is being passed to my function below

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

This is my fetcher function for SWR, and this is the error I'm getting

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

SWR hook

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

I want to know what is the type of this args that is being passed to my function below

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

This is my fetcher function for SWR, and this is the error I'm getting

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

SWR hook

const { error, data } = useSWR(`/api/albums/list/${user.id}`, fetcher)
Share Improve this question asked Oct 4, 2020 at 20:35 gabriel_tisogabriel_tiso 1,1373 gold badges13 silver badges32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

This is TypeScript signature of fetch function:

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

If you use functions rest parameters ...args, your fetcher function can be called with zero parameters like this and tsc will not report errors.

fetcher();

Or, many parameters(like four parameters):

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

Then, you use spread syntax to call the fetch API. The parameter of spread does not satisfy the function signature of fetch(the parameter can NOT be zero or more than two), so tsc reports an error.

So you'd better modify it like this:

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

package version: "typescript": "^4.1.3"

发布评论

评论列表(0)

  1. 暂无评论