You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过useQuery泛型参数重定义API响应类型?

用React Query泛型参数定义响应类型的正确写法

先修正原代码里的小笔误(getUsersQuery 应为 getUsersQueryKey),再通过 useQuery泛型参数 结合 axios.get泛型 来明确类型,替代类型断言的写法:

// 推荐用数组作为queryKey,符合React Query最佳实践
export const getUsersQueryKey = () => ["users"];

export const useUsersQuery = () =>
  // 给useQuery指定泛型:第一个是查询返回的目标类型,第二个是错误类型(可选)
  useQuery<User[], Error>(
    getUsersQueryKey(),
    // 给axios.get指定泛型,让axios直接将响应数据推断为User[]类型
    () => axios.get<User[]>("API ENDPOINT").then(response => response.data)
  );

这种写法的优势

  • 避免as User[]强制类型断言可能掩盖的类型不匹配问题,类型校验更严谨
  • 通过axios的泛型声明,从请求层面就明确了响应数据的类型,减少后续类型转换风险
  • useQuery的泛型参数直接定义了查询最终返回的数据类型,组件使用data时能获得精准的类型提示

进阶:自定义错误类型(可选)

如果需要用自定义错误类型替代默认的Error,可以在泛型中指定:

// 自定义API错误结构
interface ApiError {
  message: string;
  statusCode: number;
}

export const useUsersQuery = () =>
  useQuery<User[], ApiError>(
    getUsersQueryKey(),
    async () => {
      try {
        const response = await axios.get<User[]>("API ENDPOINT");
        return response.data;
      } catch (err) {
        // 将axios错误转换为自定义ApiError类型抛出
        throw {
          message: err.response?.data?.msg || "获取用户列表失败",
          statusCode: err.response?.status || 500
        };
      }
    }
  );

内容的提问来源于stack exchange,提问作者m_novak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:45:39