如何在NUXT中指定usefetch数据返回类型

发布于 2025-02-04 19:55:45 字数 1040 浏览 4 评论 0原文

我正在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦冥 2025-02-11 19:55:45

您可以将类型提供给usefetch来定义返回类型,

例如:

  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch<APIBody>("api_url here")

You can give a type to useFetch to define the return type

Like:

  interface APIBody {
    /* properties defined here */
  }

  const {data} = await useFetch<APIBody>("api_url here")
听风吹 2025-02-11 19:55:45

这是我在NUXT 3.9.0中的工作示例:

// /api/test.post.ts
export default defineEventHandler(async (event) => {
    const body = await readBody(event);
    return { body };
});

在任何组件或页面中:

<script lang="ts" setup>
import type { AsyncData } from 'nuxt/app';
import type { FetchError } from 'ofetch';
    
interface Body { key: string };
    
const { data: { value: { body } }, error } = await useFetch('/api/test', {
  method: 'post',
    body: {
      key: 'value',
    }
  }) as AsyncData<{ body: Body }, FetchError>;
    
// now you're getting body's properties without ts-errors
console.log(body.key); // value
</script>

It's my working example in Nuxt 3.9.0:

// /api/test.post.ts
export default defineEventHandler(async (event) => {
    const body = await readBody(event);
    return { body };
});

In any component or page:

<script lang="ts" setup>
import type { AsyncData } from 'nuxt/app';
import type { FetchError } from 'ofetch';
    
interface Body { key: string };
    
const { data: { value: { body } }, error } = await useFetch('/api/test', {
  method: 'post',
    body: {
      key: 'value',
    }
  }) as AsyncData<{ body: Body }, FetchError>;
    
// now you're getting body's properties without ts-errors
console.log(body.key); // value
</script>
燕归巢 2025-02-11 19:55:45

如果我们还需要基于pick中的

type SomeProps = {
    prop1: string;
    prop2: string;
};

export function usePropsApi() {
    const { public: { api } } = useRuntimeConfig();

    return {
        read: <T extends keyof SomeProps>({
            pick = [],
        }: {
            pick?: Array<T>;
        } = {}) => useFetch<Pick<SomeProps, T>>('/props', {
            baseURL: api,
            ...(pick.length && pick),
        }),
    };
}

类型不包括类型:

const { data } = await usePropsApi().read({
    pick: ['prop1'],
});
console.log('data.value: ', data.value?.prop1);
console.log('data.value: ', data.value?.prop2); // Property 'prop2' does not exist on type ...

If we also need a type based on what is in pick also, you can check this composable:

type SomeProps = {
    prop1: string;
    prop2: string;
};

export function usePropsApi() {
    const { public: { api } } = useRuntimeConfig();

    return {
        read: <T extends keyof SomeProps>({
            pick = [],
        }: {
            pick?: Array<T>;
        } = {}) => useFetch<Pick<SomeProps, T>>('/props', {
            baseURL: api,
            ...(pick.length && pick),
        }),
    };
}

and using like this, props other that the ones from pick[] will be excluded from type:

const { data } = await usePropsApi().read({
    pick: ['prop1'],
});
console.log('data.value: ', data.value?.prop1);
console.log('data.value: ', data.value?.prop2); // Property 'prop2' does not exist on type ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文