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

如何为useAsyncData()返回数据设置类型?解决unknown类型无法调用map问题

解决useAsyncData获取的数据无法调用map的问题

你当前代码的问题主要出在两个地方:

  • 错误定义了AsyncDataResult接口:useAsyncData本身会返回pending和error状态,不需要把这两个字段塞进接口返回的数据结构里;而且data: []的写法仅表示空数组,没有指定元素类型,TypeScript无法识别它是可遍历的数组类型。
  • 泛型参数使用错误:useAsyncData的泛型应该指定接口请求返回的数据类型,而非包含pending/error的复合结构。

修正方案

首先定义数组元素的具体类型(根据接口返回的实际字段调整):

// 定义数组中每个项的类型
interface ReportItem {
  entity: string; // 这里替换成你实际的entity类型,比如number/object等
  // 接口返回的其他字段也可以在这里补充定义
}

然后调整useAsyncData的泛型参数,直接指定返回数据为数组类型:

const {
  data: report,
  pending,
  error,
} = useAsyncData<ReportItem[]>('report', () =>
  $fetch(
    `https://${url[route.params.server]}/tb3?s=${route.params.survey}&k=${route.params.password}`,
    { method: 'get' },
  ),
)

// 此时report的类型为ReportItem[] | null,可安全调用map
const foo = report?.map((item) => item.entity)

如果不想单独定义ReportItem接口,也可以直接使用匿名数组类型:

const {
  data: report,
  pending,
  error,
} = useAsyncData<Array<{ entity: string }>>('report', () =>
  $fetch(/* 你的请求配置 */),
)

这样修改后,TypeScript就能正确识别report的数组类型,调用map方法就不会再出现类型错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:53:11