I am trying to make a generic TypeScript wrapper for RTKQ queries. The last piece of that goal that I am stuck on is getting the return type for a generic, or even specific, query. Below I will include some of the main lines of code in my test but here is a code sandbox which shows my full code.
type EndpointKey = keyof typeof api.endpoints;
type Endpoint<EndpointName extends EndpointKey> = typeof injectedAPI.endpoints[EndpointName];
type ReturnQuery<E extends EndpointKey> = Endpoint<E>["useQuery"];
// Type is Record<string, any> & UseQuerySubscriptionResult<> - where is the UseQueryStateResult<> at? Might not be relevant but seems suspicious.
type PuppiesQueryReturnType = ReturnType<ReturnQuery<"getPuppies">>;
const queryReturn: PuppiesQueryReturnType = {} as PuppiesQueryReturnType;
const { data, foo, refetch, isLoading, error } = queryReturn; // All values have type any except for refetch
I am not sure if this is a potential bug in the types for RTKQ or if there is some step I am missing or doing incorrectly.
Note: Not all of this is my original code. Much of it is copied from various posts across the internet.
It looks like the answer to my problems is the Type TypedUseQueryHookResult
from @reduxjs/toolkit/dist/query/react/buildHooks
. I can't find a reference to it in the docs but if anyone has the link please comment and I will update.
Using this I can do something like
type QueryResultInfered<E extends EndpointKey> = Endpoint<E> extends ApiEndpointQuery<
QueryDefinition<infer QueryArgs, infer BaseQuery, any, infer ResultType>,
any
>
? TypedUseQueryHookResult<ResultType, QueryArgs, BaseQuery>
: never;
there might be a simpler way to do this without the inference but this will do the trick.
Thanks to acemarke on the Reactiflux Discord for the help!