12

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?

farm command
  • 653
  • 3
  • 7
  • 18

1 Answers1

38

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");
rickdenhaan
  • 10,857
  • 28
  • 37
  • What about `response.page`, `response.status` ? It won't be typed this way. I made it work only this way: `http.get>('/breweries')` but looks too verbose. – Alexander Kim Dec 02 '21 at 04:45
  • @AlexanderKim Are you using Axios? An Axios response object [does not have](https://github.com/axios/axios#response-schema) a `.page` attribute. – rickdenhaan Dec 02 '21 at 22:43
  • Yes, indeed, sorry, i was using axios in a nuxt plugin: https://axios.nuxtjs.org/usage/#-shortcuts, hence i was in confusion. – Alexander Kim Dec 03 '21 at 03:26