【发布时间】:2021-11-23 17:29:38
【问题描述】:
我有以下两个服务调用,它们都使用方法 ConcertDates()。
private callMyFirstService(params: MyParams): Observable<MyDto> {
return this.http.post<MyDto>(params).pipe(map(response => this.convertDates<MyDto>(response)));
}
private callMySecondService(params: MyOtherParams): Observable<MyAnotherDto> {
return this.http.post<MyAnotherDto>(params).pipe(map(response => this.convertDates<MyAnotherDto>(response)));
}
由于这些方法与另一种类型的 dto 一起运行,因此我尝试实现一些在这两种情况下都可以调用的通用函数。 我有类似的东西:
private convertDates<type>(input: type): type {
for (const key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
if (typeof input[key] === 'object') {
this.convertDates(input[key]);
} else if (typeof input[key] === 'string' && this.MY_REGEXP.test(input[key])) {
input[key] = new Date(input[key]);
}
}
return input;
}
这似乎不起作用,因为我总是得到:
Type 'Date' is not assignable to type 'type[Extract<keyof type, string>]'
还有……
Argument of type 'type[Extract<keyof type, string>]' is not assignable to parameter of type 'string'.
Type 'type[string]' is not assignable to type 'string'.
有什么想法吗? 提前非常感谢!
【问题讨论】:
标签: javascript typescript templates typescript-typings typescript-generics