简体   繁体   English

Generics 在 TypeScript 中起作用

[英]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:我正在阅读这篇关于如何使用 Axios 和 TypeScript 的文章,我对方法声明有疑问,例如:

  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?为什么T等于any ,难道不是 Generics 的概念T可以是任何东西吗? Why do I need to specify it?为什么我需要指定它? Is it for readability?是为了可读性吗? Also why is R equals AxiosResponse<T> ?另外为什么R等于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?不能说 function 的返回类型是Promise<AxiosResponse<T>> ,是不是也是为了少写返回类型的代码?

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? ...难道不是 Generics 的概念T可以是任何东西吗?

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> ?另外为什么R等于AxiosResponse<T> Couldn't I just say that the return type of the function is Promise<AxiosResponse<T>> ...我不能说 function 的返回类型是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.如果您在响应中指定您期望的类型,则使用它会更简单(并且可能更适合推理),而不需要Promise包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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