【问题标题】:Typescript ReturnType problem for generic class method泛型类方法的Typescript ReturnType问题
【发布时间】:2022-01-19 01:17:24
【问题描述】:

我正在使用打字稿:4.3.5

我有一个抽象类:

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

还有一个子类:

class Child extends Parent {
  public get<{id: number}>(id: number): Observable<{id: number}> {
    ...
  }
}

我无法获取子类的get方法的ReturnType

如果我这样做:

type T = ReturnType<Child['get']>;

我希望得到 {id: string} 但它不起作用...我只是从我的 IDE 中得到的:

<{id: string}>(id: number) => Observable<{id: string}> extends ((...args: any) => infer R) ? R : any

有办法吗?谢谢

【问题讨论】:

    标签: typescript class generics return-type


    【解决方案1】:

    我认为您的代码不能按原样工作。没有可能从子类中的 get 覆盖推断出 Type,即使在您提到的 ReturnType 问题之前,代码也会失败。

    你应该像这样重构你的代码:

    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

    【讨论】:

    • 更糟糕的是 - 这是一个 syntax 错误,它被翻译成 不同于我们预期的 种表达式。 { id: number} 不是类型的有效 name(例如,type { what: no } = any 无效,public get&lt;{ this: is.not.a.name }&gt;() 也无效。OP 的语法被解析为 property使用通用匿名函数(不是 100% 确定原因)。
    • 好吧,假设我定义了一个类型:interface Person { id: number; } 我将我的孩子定义如下:class Child extends Parent { public get&lt;Person&gt;(id: number): Observable&lt;Person&gt; { ... } } 那么为什么:type Type = ReturnType is not = Observable ?
    • 好的,问题出在我的 IDE 上,谢谢 :-)
    猜你喜欢
    • 2018-10-23
    • 2021-07-13
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多