我有以下记录方法:
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 许可协议
As per TypeScript 2.2 (you can try it in the TS Playground), calling
this.logData("GET", data)
(withdata
of typeT
) gets inferred succesfully asthis.logData<T, {}>("GET", data)
.如果您使用的 TS 版本推理失败,则可以应用 David Bohunek 建议的重载。无论如何,确保第二个签名在声明之前然后定义,否则它不会参与可用的重载。