可选的泛型

新手上路,请多包涵

我有以下记录方法:

   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 方法:而不是: this.logData<T, any>('GET', data) ,我想调用 this.logData<T>('GET', data)

有没有办法做到这一点?

原文由 Marius 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

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 建议的重载。无论如何,确保第二个签名在声明之前然后定义,否则它不会参与可用的重载。

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

原文由 FstTesla 发布,翻译遵循 CC BY-SA 3.0 许可协议

TS 更新 2020:给予 void 将使泛型类型可选。

 type SomeType<T = void> = OtherType<T>;

上面给出了作为对象的默认值的答案使它成为可选但仍然赋予它价值。


默认类型值为 {} 的示例:

 type BaseFunctionType<T1, T2> = (a:T1, b:T2) => void;

type FunctionType<T = {}> = BaseFunctionType<{name: string}, T>

const someFunction:FunctionType = (a) => {

}

someFunction({ name: "Siraj" });
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Expected 2 arguments, but got 1.(2554)

游乐场链接


默认泛型类型值为 void

 type BaseFunctionType<T1, T2> = (a:T1, b:T2) => void;

type FunctionType<T = void> = BaseFunctionType<{name: string}, T>

const someFunction:FunctionType = (a) => {

}

someFunction({ name: "Siraj" })

这是一本关于使泛型可选的好读物。

Typescript 中的可选泛型类型

游乐场链接

原文由 Siraj Alam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进