简体   繁体   中英

Generics functions in TypeScript

I was reading this article about how to use Axios with TypeScript and I had a question about the methods declaration, for example:

  get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> {
    return this.http.get<T, R>(url, config);
  }

  delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> {
    return this.http.delete<T, R>(url, config);
  }

Now, what I miss to understand is the this syntax:

<T = any, R = AxiosResponse<T>>

Why is the T equal to any , isn't it the concept of Generics that T can be anything? Why do I need to specify it? Is it for readability? Also why is R equals AxiosResponse<T> ? Couldn't I just say that the return type of the function is Promise<AxiosResponse<T>> , is it also the sake of writing less code in the return type?

Those are defaults that are used when the type isn't specified and can't be inferred.

...isn't it the concept of Generics that T can be anything?

Not necessarily, generic type parameters can be constrained , but yes in this case.

Why do I need to specify it?

You don't need to (but you can), there's a default if you don't and it can't be inferred from the call site.

Also why is R equals AxiosResponse<T> ? Couldn't I just say that the return type of the function is Promise<AxiosResponse<T>> ...

It's simpler (and probably better for inference) to use if you specify the type of what you're expecting in the response, without the Promise wrapper on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM