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

React Query+TypeScript中useQuery类型与map方法报错问题排查

React Query + TypeScript 自定义Hook错误修复

遇到的两个错误

  1. queryKey类型错误:

No overload matches this call. The last overload gave the following error. Argument of type '{ queryKey: string[]; queryFn: () => Promise<FetchResponse | Recommendations[]>; }' is not assignable to parameter of type 'QueryKey'. Object literal may only specify known properties, and 'queryKey' does not exist in type 'readonly unknown[]'.ts(2769)

  1. map方法调用错误:

Property 'map' does not exist on type 'NonNullable'

问题根源

  1. 泛型声明不匹配:useQuery泛型参数声明的是FetchResponse<Recommendations>,但queryFn实际返回的是Recommendations[](接口返回的latestrecs数组),类型冲突导致TypeScript错误推断参数结构,把配置对象当成了QueryKey类型。
  2. 数据类型推断错误:泛型错误导致useQuery返回的数据类型识别异常,无法被判定为数组,因此调用map方法时触发类型报错。

修复方案

1. 修正useQuery泛型类型

将useQuery的泛型第一个参数改为Recommendations[],与queryFn的返回值类型对齐:

import { useQuery } from "@tanstack/react-query";
import apiTest from "../../Services/api-test";

export interface Recommendations {
  title_description: string;
  title_id: number;
  title_name: string;
}

export interface FetchResponse<T> {
  latestrecs: T[];
  watchlist: T[];
}

const useRecommendations = () =>
  // 泛型改为Recommendations[],匹配queryFn返回的数组类型
  useQuery<Recommendations[], Error>({
    queryKey: ['recommend'],
    queryFn: () =>
      apiTest.get<FetchResponse<Recommendations>>("/titles")
        .then((res) => res.data.latestrecs),
  })

export default useRecommendations;

2. 修复遍历代码的类型问题

修正泛型后,useQuery返回的data类型变为Recommendations[] | undefined,此时recommendations?.map会被TypeScript正确识别为数组方法:

{recommendations?.map((title) => (
  <ul key={title.title_id} style={{ margin: 0, padding: 0 }}>
    <div className={styles.title} onClick={() => navigate("/title")}>
      {title.title_name}
    </div>
  </ul>
))}

扩展说明

后续要单独封装watchlist的Hook时,只需复用现有逻辑,修改queryKey和返回值即可:

const useWatchlist = () =>
  useQuery<Recommendations[], Error>({
    queryKey: ['watchlist'],
    queryFn: () =>
      apiTest.get<FetchResponse<Recommendations>>("/titles")
        .then((res) => res.data.watchlist),
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:47:28