Keselme
Keselme

Reputation: 4279

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?

Upvotes: 0

Views: 71

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

Those are defaults that are used when the type isn't specified and can't be inferred. (Kind of like function parameter defaults, function foo(a = 42) says a is 42 if [loosely speaking] it's not provided.)

...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. If the = any weren't there, then you would have to specify it.

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 to use (and probably better for inference) if you specify the type of what you're expecting in the response, without the Promise wrapper on it.

const thingy = await axios.get<ThingyType>("...");

Upvotes: 1

Related Questions