Reputation: 693
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?
Upvotes: 14
Views: 35635
Reputation: 11328
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");
Upvotes: 45