11

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)
gabriel_tiso
  • 1,007
  • 3
  • 11
  • 27

1 Answers1

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"

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Since you're not doing anything with additional arguments beyond the first two, wouldn't it be better just to leave off the `...args` entirely? – SimonW Jan 19 '21 at 06:51
  • @SimonW Yes, I’m not sure if the `fetcher` needs other parameters. So I keep `...args` – Lin Du Jan 19 '21 at 07:15
  • Hi, do you have an example of how it would be used? I am left wondering, how should I make the call to the fetcher passing it the init object with its values. Example: `const {data, error} = useSWR("/some/path", fetcher("some/path", {headers: {}}))` What would be the correct way? – chalo Jan 04 '22 at 14:51