可选的通用类型 [英] Optional generic type
问题描述
我有以下日志记录方法:
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)
(类型为T
的data
)为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屋!