TypeScript Error - Expected 1-2 arguments, but got 0 or more. TS2556

Viewed 4496

I was using this statement in JavaScript but when I try to use it in a TypeScript Project I get an error. It's complaining about the fetch(...args)

const fetcher = (...args) => fetch(...args).then(response => response.json());

Expected 1-2 arguments, but got 0 or more.  TS2556
2 Answers

This should help you:

const fetcher = (...args: [input: RequestInfo, init?: RequestInit | undefined]) => fetch(...args).then(response => response.json());

You should explicitly type arguments for fetch. It expects 1-2 arguments.

If you want to use rest operator, you should tell TS, that you also expect two arguments in your higher order function

UPDATE

Generic approach. If you want to get type of arguments of any function, just use Parameters util.

type FetchParameters = Parameters<typeof fetch>

Taking this answer from comment by @Keith which was the only thing that worked for me:

const fetcher = (...args: Parameters<typeof fetch>) => {
  fetch(...args).then(response => response.json());
}

Specifically adding this Parameters<typeof fetch> as the type of ...args

Related