简体   繁体   English

通用 class 方法的 Typescript ReturnType 问题

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

TypeScript playground TypeScript操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript:通用参数/ReturnType 和字符串枚举有问题 - Typescript: Problem with generic Parameter/ReturnType and string Enums 通用函数的 Typescript ReturnType - Typescript ReturnType of generic function TypeScript - 通用函数的 ReturnType 不起作用 - TypeScript - ReturnType of a generic function not working TypeScript - 包含其他泛型类型的 class 字典泛型 - 泛型类型在方法内部丢失的问题 - TypeScript - class dictionary generic that holds other generic types - problem with generic types being lost inside method 函数返回函数的通用TypeScript类型,该函数将ReturnType替换为返回函数的ReturnType - Generic TypeScript Type for functions returning functions that replaces the ReturnType with the ReturnType of the returned function 将typescript ReturnType与keyof和通用类型的迭代键一起使用 - Using typescript ReturnType with keyof and iterated keys of generic type 我可以将 function(并获取其 ReturnType)传递给通用 TypeScript 类型吗? - Can I pass a function (and get its ReturnType) to a generic TypeScript type? Typescript 方法的 class 泛型类型允许任何 - Typescript method of class generic type allows any 如何在打字稿中向泛型类的原型添加方法 - How to add a method to a prototype of a generic class in typescript TypeScript:如何访问泛型类的静态方法 - TypeScript: how to access a static method of a generic class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM