简体   繁体   中英

Typescript ReturnType problem for generic class method

I'm using typescript: 4.3.5

I have an abstract class:

abstract class Parent {
  public get<Type>(id: number): Observable<Type> {
    ...
  }
}

and a child 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

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}>(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.

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']>;

TypeScript playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM