Answer the question
In order to leave comments, you need to log in
How does typing work in this case?
There is a code that calls to the backend using the axios library.
interface ResponseApi {
status: string;
data: any;
}
async signIn(postData: LoginFormProps): Promise<ResponseApi> {
const { data } = await axios.post<ResponseApi>('/auth/login', {
username: postData.email,
password: postData.password,
});
return data;
},
post<T = any, R = AxiosResponse<T>>
we create a context from Generics, which we can use everywhere, and even in the response "Promise:"R";" . Do I understand correctly?. ps there were no such examples in the textbookpost<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
Answer the question
In order to leave comments, you need to log in
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
Both generics have default types, which means that if they are not specified, they will be used axios.post<ResponseApi>(/* ... */)
T
ResponseApi
AxiosResponse<T>
AxiosResponse<ResponseApi>
R
{
data: ResponseApi;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
it gets into the return type wrapped in a Promise, but TS knows about the behavior of await and destructuring, and therefore calculates the type for data
-ResponseApi
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question