如何获取RTKQ中UseQuery定义的ReturnType类型
解决RTKQ通用查询返回类型获取问题
你的问题出在未正确处理RTKQ中useQuery泛型函数的类型推导:直接取Endpoint<E>["useQuery"]只是拿到了泛型函数的签名,未指定具体泛型参数时,TypeScript会默认使用最宽泛的类型,导致返回类型丢失,大部分属性变成any。
修正方案1:利用RTKQ内置类型与端点定义提取类型
import type { UseQueryResult } from '@reduxjs/toolkit/query/react'; type EndpointKey = keyof typeof api.endpoints; // 提取指定端点的查询定义类型 type EndpointQueryDef<E extends EndpointKey> = typeof api.endpoints[E] extends { query: infer Q; } ? Q : never; // 提取查询的返回数据类型 type QueryResponseData<E extends EndpointKey> = EndpointQueryDef<E>['responseType']; // 生成正确的useQuery返回类型 type QueryReturnType<E extends EndpointKey> = UseQueryResult<QueryResponseData<E>, unknown>; // 现在PuppiesQueryReturnType会拥有完整的类型定义 type PuppiesQueryReturnType = QueryReturnType<'getPuppies'>; const queryReturn: PuppiesQueryReturnType = {} as PuppiesQueryReturnType; const { data, refetch, isLoading, error } = queryReturn; // 所有属性类型均正确推导
修正方案2:为泛型useQuery指定参数类型
如果你的查询需要传入参数,可通过指定泛型参数的方式直接推导返回类型:
type EndpointKey = keyof typeof api.endpoints; type Endpoint<E extends EndpointKey> = typeof api.endpoints[E]; // 针对无参数的查询,传入[]作为参数类型 type QueryReturnType<E extends EndpointKey> = ReturnType<Endpoint<E>['useQuery']>; // 若查询需要参数(比如getPuppies需要{ count: number }),则调整为: // type QueryReturnType<E extends EndpointKey> = ReturnType<Endpoint<E>['useQuery']<[{ count: number }]>>; type PuppiesQueryReturnType = QueryReturnType<'getPuppies'>;
原因说明
RTKQ的useQuery是泛型函数,其返回类型依赖于查询参数、返回数据等泛型参数。未指定这些参数时,TypeScript无法推导具体类型,只能返回最宽泛的Record<string, any> & UseQuerySubscriptionResult,导致属性类型丢失。这并非RTKQ的类型bug,而是泛型类型推导的正常表现。
内容的提问来源于stack exchange,提问作者Grant
相关产品推荐
相关产品推荐

