如何使用类型作为来自 axios.get 的响应 [英] how to use a type for the response from axios.get

查看:31
本文介绍了如何使用类型作为来自 axios.get 的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 Axios 获取数据的简单代码:

I have a simple code to fetch data via Axios:

const response= await axios.get("blabla");

现在我正在尝试使用打字稿.

and now I'm trying to use typescript.

当我将类型添加到 get 方法时,它会起作用:

When I add the type to the get method it works:

const response= await axios.get<Todo[]>("blabla");

但我需要的是:

const response:Todo[] = await axios.get("blabla");

但如果我这样做,我会在 response.data 上收到错误消息:属性 'data' 在类型 'Todo[]' 上不存在

but if i do that i get an error on response.data saying: Property 'data' does not exist on type 'Todo[]'

所以 2 个问题:1)为什么第一种方法没有发生?2)第二种方式怎么做?

so 2 questions: 1) why didn't it happen for the first approach? 2) how to do the second way?

推荐答案

axios.get() 返回一个 AxiosResponse 对象,其中 response.数据any.

axios.get() returns an AxiosResponse<any> object, where response.data is any.

axios.get() 返回一个 AxiosResponse 对象,其中 response.dataTodo[].

axios.get<Todo[]>() returns an AxiosResponse<Todo[]> object, where response.data is Todo[].

所以你可以输入 response 为:

So you can type response as:

const response: AxiosResponse<Todo[]> = await axios.get("blabla");

这篇关于如何使用类型作为来自 axios.get 的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆