可选的通用类型 [英] Optional generic type

查看:61
本文介绍了可选的通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日志记录方法:

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;
  }

requestData是可选的,当我不将requestData发送给方法时,我希望能够在不必指定S类型的情况下调用logData:我想打电话给this.logData<T>('GET', data).

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?

推荐答案

根据TypeScript 2.2(可以在TS Playground中尝试),成功调用this.logData("GET", data)(类型为Tdata)为this.logData<T, {}>("GET", data).

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<T, {}>("GET", data).

如果您使用的TS版本推断失败,则可以应用David Bohunek建议的重载.无论如何,请确保先声明第二个签名,然后再对其进行定义,否则它将不参与可用的重载.

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<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
}

这篇关于可选的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆