Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetcher argument type inference fails when useSWR-hook is explicitly typed #3005

Open
petetnt opened this issue Aug 19, 2024 · 0 comments
Open

Comments

@petetnt
Copy link

petetnt commented Aug 19, 2024

Bug report

Description / Observed Behavior

When looking at the documentation, one can either use a typed fetcher or type the useSWR hook directly. Let's try to implement the token example from the same docs (https://swr.vercel.app/docs/arguments.en-US#multiple-arguments)

If a typed fetcher is used, everything works just fine.

const fetcher = async<T>(url: string, token: string): Promise<T> {
  // fetch stuff
}

// then...

type Foobar = {
  foo: string,
  bar: string
}

const token = 'FOOBAR';

const {
  data,
  error,
  isLoading
} = useSWR(['foobar.com/api/foo', token], ([url, token]) => fetcher<Foobar>(url, token));

Everything works just fine here, the types passed into the fetcher are correctly set to string and string.

However now the error return value is any, but we can also type the useSWR hook:

const {
  data,
  error,
  isLoading
} = useSWR<Foobar, Error>(['foobar.com/api/foo', token], ([url, token]) => fetcher(url, token));

However now the url and token are any and unknown respectively. Any extra arguments passed are also unknown instead of their actual type, eg. ['foobar.com', 1, false, 'foo'] results into string, unknown, unknown, unknown.

Expected Behavior

I'd expect that the data would be of type Foobar and the url and token parameters would be string and string.

Repro Steps / Code Example

Repro steps above.

Additional Context

SWR version: 2.2.5

This issue also makes it annoying to use a type fetcher, because there's no way to annotate the Error type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant