如何在NUXT中指定usefetch数据返回类型
我正在NUXT3中的API获取数据。我正在使用TypeScript,并希望定义我将获得的数据类型。我该如何指定?
<script lang="ts" setup>
interface APIBody {
/* properties defined here */
}
const {data} = await useFetch("api_url here")
</script>
<template>
{{ data.name.officialName }}
<template>
我在template
中遇到一个错误,其中我正在显示data.name.officialname
属性'名称'不存在于类型'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>
在这种情况下,错误是:
'ref&lt; pick&lt;未知的转换,从不键入'apibody []'可能是一个错误
I am fetching data from an API in Nuxt3. I am using typescript and I wish to define the type of data that I will get. How do I specify this?
<script lang="ts" setup>
interface APIBody {
/* properties defined here */
}
const {data} = await useFetch("api_url here")
</script>
<template>
{{ data.name.officialName }}
<template>
I get an error in the template
where I am displaying data.name.officialName
Property 'name' does not exist on type 'never'
However, while running the code in the browser, the website works fine.
Edit
I tried the following code but I am receiving a different error now.
<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>
The error in this case is:
Conversion of type 'Ref<Pick<unknown, never>>' to type 'APIBody[]' may be a mistake because neither type sufficiently overlaps with the other.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将类型提供给
usefetch
来定义返回类型,例如:
You can give a type to
useFetch
to define the return typeLike:
这是我在NUXT 3.9.0中的工作示例:
在任何组件或页面中:
It's my working example in Nuxt 3.9.0:
In any component or page:
如果我们还需要基于
pick
中的类型不包括类型:
If we also need a type based on what is in
pick
also, you can check this composable:and using like this, props other that the ones from
pick[]
will be excluded from type: