Nuxt3中useFetch能否指定返回类型?指定后类型报错如何解决?
在Nuxt3中为useFetch指定返回类型的解决方案
Nuxt3的useFetch完全支持指定返回类型,你遇到的报错是因为data的类型处理逻辑导致的——useFetch返回的data是Ref类型,默认包含null的可能性,加上内部类型工具的推导规则,才出现了类型识别问题。下面是几种可行的解决方式:
解决方法
方式1:添加存在性判断缩小类型范围
先判断data.value不为空,TypeScript会自动推导其为你指定的APIBody类型:
type APIBody = { test: string } const { data, error } = await useFetch<APIBody>("api_url here") if (data.value) { console.log(data.value.test) // 此处类型会被正确识别为APIBody }
方式2:直接断言数据类型
在访问data.value时明确断言其类型:
type APIBody = { test: string } const { data, error } = await useFetch<APIBody>("api_url here") console.log((data.value as APIBody).test)
方式3:通过transform函数明确类型
利用useFetch配置项中的transform函数,强制转换返回值类型:
type APIBody = { test: string } const { data, error } = await useFetch<APIBody>("api_url here", { transform: (response) => response as APIBody }) if (data.value) { console.log(data.value.test) }
报错原因说明
useFetch返回的data本质是Ref<APIBody | null>类型,当你直接访问data.value.test时,TypeScript无法确认data.value是否为null,再结合Nuxt内部的PickFrom类型工具,就会出现类型不匹配的报错。通过上述方式明确类型或做非空判断,就能解决这个问题。
内容的提问来源于stack exchange,提问作者harunaga
相关产品推荐
相关产品推荐

