[英]Typescript ReturnType problem for generic class method
I'm using typescript: 4.3.5我正在使用 typescript: 4.3.5
I have an abstract class:我有一个抽象的 class:
abstract class Parent {
public get<Type>(id: number): Observable<Type> {
...
}
}
and a child class:和一个孩子 class:
class Child extends Parent {
public get<{id: number}>(id: number): Observable<{id: number}> {
...
}
}
I cannot get the ReturnType of the get method for the child class我无法获取子 class 的 get 方法的 ReturnType
If i do this:如果我这样做:
type T = ReturnType<Child['get']>;
I expect to get {id: string} but it does not work... I just get from my IDE:我希望得到 {id: string} 但它不起作用......我只是从我的 IDE 得到:
<{id: string}>(id: number) => Observable<{id: string}> extends ((...args: any) => infer R) ? R : any
Is there a way to do it?有没有办法做到这一点? thanks
谢谢
I don't think your code works as is.我不认为您的代码按原样工作。 There is no possible inference of
Type
from a get
override in a child class which makes the code fail even before the ReturnType
issue you are mentioning.没有可能从子 class 中的
get
覆盖推断Type
,这甚至在您提到的ReturnType
问题之前使代码失败。
You should refactor your code like this:您应该像这样重构您的代码:
abstract class Parent<Type> {
public get(id: number): Type {
// ...
}
}
class Child extends Parent<Observable<{ id: number }>> {
public get(id: number): Observable<{ id: number }> {
}
}
type T = ReturnType<Child['get']>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.