Issue
I have created a generic useAsync hook using axios.
At the moment, for some reason I can't work out, the response is inferred as unknown
instead of AxiosResponse<MyOwnType>
I have a working playground which illustrates the issue.
data
is typed as unknown
which is incorrect.
Solution
What you are trying to do here isn't really possible with TypeScript:
// Can't define a second generic by a `unknown` generic type
const useAsync = <D, F extends PromiseFn<D>>(promiseFn: F) => {
1- So, what you should do instead, is to remove the D
generic from the function's signature.
2- The second part, is moving the asyncReducer
function inside of your own hook and leverage the already defined F
generic.
const useAsync = <F extends PromiseFn<any>>(promiseFn: F) => {
const asyncReducer = (
state: AsyncState<AxiosResponseType<F>>,
action: AsyncAction<AxiosResponseType<F>>
): AsyncState<AxiosResponseType<F>> => {
...
3- You can now remove the type assertion you have on line 68 and pass in the generic's return type by defining the following type:
type AxiosResponseType<F extends PromiseFn<any>> = Awaited<ReturnType<F>>;
4- Use this new generic to type state
, action
and the return type of the reducer, and you should be good to go!
Answered By - Pedro Figueiredo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.