Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a type for the response from axios.get

I have a simple code to fetch data via Axios:

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

and now I'm trying to use typescript.

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");

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

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

like image 722
farm command Avatar asked Aug 23 '19 15:08

farm command


1 Answers

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

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

So you can type response as:

const response: AxiosResponse<Todo[]> = await axios.get("blabla");
like image 57
rickdenhaan Avatar answered Sep 23 '22 08:09

rickdenhaan