如何将类型用于axios.get的响应 [英] how to use a type for the response from axios.get

查看:100
本文介绍了如何将类型用于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");

但是我需要的是这样的:

but what i need is something like:

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

但是如果我这样做,我会在 response.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< any> 对象,其中响应.数据任何.

axios.get< Todo []>()返回 AxiosResponse< Todo []> 对象,其中 response.data Todo [] .

因此您可以将 response 输入为:

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

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

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