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?
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.
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.
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.
As of TypeScript 2.3, you can use generic parameter defaults.
private logData<T, S = {}>(operation: string, responseData: T, requestData?: S) { // your implementation here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With