0

The React data fetching library SWR has an example using the library with typescript here. In the example, a fetcher function is defined that wraps fetch and which is then passed to the useSWR hook to do the actual data fetching.

export default async function fetcher<JSON = any>(
  input: RequestInfo,
  init?: RequestInit
): Promise<JSON> {
  const res = await fetch(input, init)
  return res.json()
}

While not immediately clear from the repo, this results in an typescript-eslint warning due to an unexpected any. Below is a screen shot from my editor showing the warning:

Eslint warning from my local setup

I'm a little unclear as to what's the correct way to handle the any type here? Should I replace it with unknown? Or should I define a custom type?

P4nd4b0b3r1n0
  • 1,951
  • 3
  • 22
  • 31
  • 2
    Well you could perhaps capture the idea of "returns some sort of json" better by using a custom type: `type JSONV = null | string | number | boolean | {[k: string]: JSONV}; type JSONObj = Record;`, then: `async function fetcher(...)`. However this will still be cumbersome to use in practice if you don't know the format of your response beforehand as it will require a lot of casting / narrowing before you can use the values. Ideally you should just specify the exact response shape at the call site: `const resp = await fetcher<{foo: string, bar: number}>(...);`. – CRice Nov 10 '21 at 18:01
  • 2
    "Should I replace it with unknown? Or should I define a custom type?" Whichever one of those – Roberto Zvjerković Nov 10 '21 at 18:16

0 Answers0