【问题标题】:Infer class generic property method return type推断类泛型属性方法返回类型
【发布时间】:2021-06-11 15:26:19
【问题描述】:

我无法推断类泛型属性的返回类型。

我有一个有效的简单设置:

class A<T extends B> {
  constructor(public b: T) {}

  getB() {
    return this.b
  }

  bMethodResult() {
    return this.b.methodOne()
  }
}

class B {
  methodOne() {
    return { status: 'ok' }
  }
}

const aOne = new A(new B())

aOne.getB() // :B

aOne.bMethodResult() // {status:string}

如您所见,TS 正确推断出aOne.bMethodResult() 的返回类型。 但是,如果我尝试传入具有不同方法签名的 B 类的子类,则 TS 不会将返回类型更新为 B 子类方法。

class BChild extends B {
  methodOne() {
    return { status: 'ok', data: true }
  }
}

const aTwo = new A(new BChild())

aTwo.getB() // : BChild // ok

aTwo.bMethodResult() // : {status:string }
// I want it to be {status:string, data:boolean}

有没有办法获得 child 类的返回类型?

TS Playground

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    您可以通过向bMethodResult 添加返回类型来做到这一点:

    class A<T extends B> {
      // ...
    
      bMethodResult(): ReturnType<T['methodOne']> {
        return this.b.methodOne() as ReturnType<T['methodOne']>
      }
    }
    
    // ...
    
    aTwo.bMethodResult() // : {status:string, data: boolean}
    

    但是,这需要类型断言,因为 TypeScript 将 this.b.methodOne() 推断为 {status: string} 而不是 ReturnType&lt;T['methodOne']&gt;。

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多