调用API时如何将类型分配给API响应

发布于 2025-02-13 18:23:11 字数 412 浏览 0 评论 0原文

我在项目中使用打字稿,当我使用获取来调用API时,响应的类型是任何。

const response = await fetch(url);

我知道此响应的数据结构是一个对象,

{id: string; code: string}

我可以使用以下方式将类型分配给响应?如果没有,我可以了解此要求的最佳实践吗?

const response: {id: string; code: string} = await fetch(url); 

如果我只需要ID,可以这样做吗?

   const { id }: {id: string} = await fetch(url);

I am using TypeScript in my project and when I use fetch to call the API, the type of response is any.

const response = await fetch(url);

I know the data structure of this response is an object

{id: string; code: string}

Can I use below way to assign the type to response? If not, may I please know the best practise for this requirement?

const response: {id: string; code: string} = await fetch(url); 

If I only need id, is it ok to do so?

   const { id }: {id: string} = await fetch(url);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

孤独陪着我 2025-02-20 18:23:11

您应该创建键入获取并在需要打字响应的地方使用它:

async function typedFetch<T>(url: string): Promise<T> {
  const response = await fetch(url);
  const data = await response.json();
  return data as T;
}

// Consumer
const response = await typedFetch<YourCustomType>('some/api/1'); // Here response will be of `YourCustomType` type

You should create typed fetch and use it where you need typed response:

async function typedFetch<T>(url: string): Promise<T> {
  const response = await fetch(url);
  const data = await response.json();
  return data as T;
}

// Consumer
const response = await typedFetch<YourCustomType>('some/api/1'); // Here response will be of `YourCustomType` type
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文