Optional generic type

Marius picture Marius · May 30, 2016 · Viewed 80.6k times · Source

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?

Answer

kimamula picture kimamula · May 4, 2017

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

private logData<T, S = {}>(operation: string, responseData: T, requestData?: S) {
  // your implementation here
}