V
V
Vann Damm2021-01-13 22:29:53
typescript
Vann Damm, 2021-01-13 22:29:53

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;
  },

What interests me is the typing of the post method. He takes two generics. We pass one, and at the same time, to the generic R - by default we assign the type into which we pass the generic T. i.e. in fact, when describing types for the function, in this place 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 textbook
post<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

1 answer(s)
D
Dmitry Belyaev, 2021-01-13
@effect_tw

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
. When we call , we explicitly indicate that is the type , and R is taken by default, that is , which in our case corresponds to , and if we continue to expand , then it turns out that - thisaxios.post<ResponseApi>(/* ... */)TResponseApiAxiosResponse<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 question

Ask a Question

731 491 924 answers to any question