HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModerate

How can I make a generic type optional?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typeoptionalgenericcanhowmake

Problem

I have the following logging method:
private logData(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('GET', data), I want to call this.logData('GET', data).

Is there a way to achieve this?

Solution

As per TypeScript 2.2 (you can try it in the TS Playground), calling this.logData("GET", data) (with data of type T) gets inferred succesfully as this.logData("GET", data).

The overload suggested by David Bohunek can be applied if the inference fails with the TS version you use. Anyway, ensure that the second signature is before declared and then defined, otherwise it would not participate in the available overloads.

// Declarations
private logData(operation: string, responseData: T);
private logData(operation: string, responseData: T, requestData?: S);
// Definition
private logData(operation: string, responseData: T, requestData?: S) {
    // Body
}

Code Snippets

// Declarations
private logData<T>(operation: string, responseData: T);
private logData<T, S>(operation: string, responseData: T, requestData?: S);
// Definition
private logData<T, S>(operation: string, responseData: T, requestData?: S) {
    // Body
}

Context

Stack Overflow Q#37525094, score: 29

Revisions (0)

No revisions yet.