swr
swr copied to clipboard
Fetcher argument type inference fails when useSWR-hook is explicitly typed
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.