'any type of I can designate in generic types in axios.get method with TypeScript
axios.get('/api')
When I code with TypeScript like above, I should better designate types as I can reference the type definition of axios as below.
(method) AxiosInstance.get<any, AxiosResponse<any>>(url: string, config?: AxiosRequestConfig | undefined): Promise<AxiosResponse<any>>
^^^ <- ???
I can't understand the any type of the 1st one of generic types of get method AxiosInstance.get<any,. What for shall this any be used?
Solution 1:[1]
Take a look at the axios type definitions.
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
The first type argument is the type that is returned by the api. This defaults to any.
The second is the type of response. This defaults to a response that carries the type if the first argument.
Solution 2:[2]
The first argument of Axios type generics refers only to the data property of the response object (which is the result of a request call), this may be a little be redundant if you also use the second argument, because the second one refers to the entire response object, including not only data, but config, headers, status and statusText. There is also a third parameter that will be reflected in the request parameters, the use cases are demonstrated below:
import { Axios, AxiosResponse } from 'axios';
type MyStatus = 200 | 404
type MyResponseData = { test: string, total: number }
type MyRequestData = { page: number }
interface CustomResponse extends AxiosResponse {
status: MyStatus;
// you can also override response data here
}
(new Axios('/')).get<
MyResponseData,
CustomResponse,
MyRequestData,
>('/test',
// The typing here follows MyRequestData
{ data: {page: 1} }
// The typings of res follows MyResponseData
// and also, res.data has CustomResponse types
).then(res => {
// typeof res.data = MyResponseData
// typeof res.status = MyStatus
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
