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

选取Query查询结果值时出现TS2339类型错误filter属性不存在

问题描述

编写从Query查询结果中选取值的逻辑时遇到TS报错,自行排查未解决。

复现流程

  • 首先通过接口查询获取到对象数组,返回结构如下:
[
  {
    chosenDoughType: "Thin",
    chosenSize: 26,
    doughTypes: (2) [{…}, {…}],
    id: "yHYRVvZlnAZ6jXG9kzI4B",
    pizzaId: "fMtMxzIkRTsHEwHsSvGvi",
    sizes: (3) [{…}, {…}, {…}]
  },
  // 其余为结构相同的对象
]
  • 编写如下代码,希望筛选出带有指定id的单个对象:
interface SpecType {
    id: string
    doughTypes: object[]
    sizes: object[]
    chosenDoughType: string
    chosenSize: number
    pizzaId: string
}
const { oneSpecData, isLoading, isSuccess, isError } = useGetSpecsQuery(undefined, {
    selectFromResult: result => ({
        ...result,
        oneSpecData: result.filter((item: SpecType): boolean => {
            return item.id !== specId
        }),
    }),
})
  • 运行后抛出如下TS错误:
TS2339: Property 'filter' does not exist on type 'UseQueryStateDefaultResult<QueryDefinition<void, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, never, SpecType[], "api">>'.
  Property 'filter' does not exist on type '{ error?: undefined; data?: undefined; fulfilledTimeStamp?: undefined; originalArgs?: undefined; requestId?: undefined; endpointName?: string | undefined; startedTimeStamp?: undefined; status: QueryStatus.uninitialized; ... 5 more ...; isUninitialized: true; } & { ...; }'.
    55 |         selectFromResult: result => ({
    56 |             ...result,
  > 57 |             oneSpecData: result.filter((item: SpecType): boolean => {
       |                                 ^^^^^^
    58 |                 return item.id !== specId
    59 |             }),
    60 |         }),

初步推测问题和类型定义相关,但不清楚具体修复方式。

报错原因
  • selectFromResult 回调接收的result参数是完整的查询状态对象,包含isLoading、isError、data等字段,并非接口直接返回的SpecType[]数组,因此直接在result上调用数组方法filter会触发类型错误。
  • 查询处于未初始化、加载中、请求失败状态时,接口返回的数组会挂载在result.data字段上,且此时data值为undefined,直接操作也会出现运行时错误。
  • 现有筛选逻辑存在两处错误:一是判断条件写反(!==会过滤掉目标id的项),二是要获取单个指定id对象应该用find而非filter(filter返回匹配项组成的数组)。
修复代码

对result.data做空值保护后再执行查找逻辑,修正筛选判断条件即可:

interface SpecType {
    id: string
    doughTypes: object[]
    sizes: object[]
    chosenDoughType: string
    chosenSize: number
    pizzaId: string
}
const { oneSpecData, isLoading, isSuccess, isError } = useGetSpecsQuery(undefined, {
    selectFromResult: result => ({
        ...result,
        // 先判断data存在再执行查找,找不到时oneSpecData为undefined
        oneSpecData: result.data?.find((item: SpecType) => item.id === specId),
    }),
})

如果确实需要返回数组形式的匹配结果,把find换回filter、增加空值兜底即可:

oneSpecData: result.data?.filter((item: SpecType) => item.id === specId) ?? [],

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 14:09:26