Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional generic type

I have the following logging method:

  private logData<T, S>(operation: string, responseData: T, requestData?: S) {     this.logger.log(operation + ' ' + this.url);     if (requestData) {       this.logger.log('SENT');       this.logger.log(requestData);     }     this.logger.log('RECEIVED');     this.logger.log(responseData);     return responseData;   } 

The requestData is optional, I want to be able to call logData without having to specify the S type when I don't send the requestData to the method: instead of: this.logData<T, any>('GET', data), I want to call this.logData<T>('GET', data).

Is there a way to achieve this?

like image 265
Marius Avatar asked May 30 '16 11:05

Marius


People also ask

How do I make my generic optional?

To make a generic type optional, you have to assign the void as the default value. In the example below, even though the function takes a generic type T, still you can call this function without passing the generic type and it takes void as default.

How do you make a generic type optional in TypeScript?

As of TypeScript 2.3, you can use generic parameter defaults. Curious if using S = never would enforce the type get specified when the optional parameter is used.

What is a generic type in TypeScript?

Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type. So, components can be called or used with a variety of data types. Generics in TypeScript is almost similar to C# generics.


1 Answers

As of TypeScript 2.3, you can use generic parameter defaults.

private logData<T, S = {}>(operation: string, responseData: T, requestData?: S) {   // your implementation here } 
like image 158
kimamula Avatar answered Sep 19 '22 22:09

kimamula