Nuxt3中如何指定useFetch返回数据的TypeScript类型
Nuxt3 useFetch 正确指定TypeScript返回类型方案
问题描述
在Nuxt3 + TypeScript项目中调用接口获取数据时,初始实现代码如下:
<script lang="ts" setup> interface APIBody { /* properties defined here */ } const {data} = await useFetch("api_url here") </script> <template> {{ data.name.officialName }} </template>
模板渲染data.name.officialName时触发TypeScript报错:
Property 'name' does not exist on type 'never'
该代码在浏览器中实际运行时网站功能完全正常。
后续尝试手动标注类型时触发了新的报错,尝试代码如下:
<script lang="ts" setup> interface APIBody { /* properties defined here */ } const typedData = ref<APIBody[]>() const {data} = await useFetch("api_url here") typedData.value = data as APIBody[] // -> error here </script> <template> {{ data.name.officialName }} </template>
对应报错信息为:
Conversion of type 'Ref<Pick<unknown, never>>' to type 'APIBody[]' may be a mistake because neither type sufficiently overlaps with the other.
解决方法
useFetch 原生支持泛型参数直接声明返回数据类型,无需额外定义ref做强制转换,这是官方推荐的类型标注方式:
- 先按照接口实际返回结构完整定义
APIBody类型 - 调用
useFetch时传入泛型参数,指定返回data的类型 - 模板访问嵌套属性时建议添加可选链
?.,匹配请求加载阶段data为null的初始状态
正确示例代码:
<script lang="ts" setup> // 按接口实际返回结构定义类型 interface APIBody { name: { officialName: string // 补充其余实际返回字段 } // 补充其余实际返回字段 } // 单条数据返回用 useFetch<APIBody>,数组返回用 useFetch<APIBody[]> const { data } = await useFetch<APIBody>("api_url here") </script> <template> {{ data?.name.officialName }} </template>
之前写法报错的原因
- 初始写法未指定泛型时,TS无法推导接口返回结构,会将
data类型推导为never,因此访问属性时报错 - 手动强转写法的问题在于,
useFetch返回的data本身是Ref类型,直接将Ref对象强转为APIBody[]属于类型不匹配;即使取data.value做转换,也属于冗余写法,没有直接使用泛型简洁。
内容的提问来源于stack exchange,提问作者Nishant Jalan
相关产品推荐
相关产品推荐

