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?
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?
-
1
Instead of
any
you should put there the type of the Model/Data that this request returns; likeaxios.get<IUser>('/api/user/12345')
And leave the second type empty. Maybe it would have been better to not put in this second Type there at all and instead describe the method asget<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
– Thomas Commented Aug 4, 2019 at 9:07
2 Answers
Reset to default 5Take 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.
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
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744310558a4567925.html
评论列表(0条)