推断类泛型属性方法返回类型

时间:2021-03-13 23:57:38

标签: typescript typescript-generics

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

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

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}

有没有办法获取类的返回类型?

TS Playground

1 个答案:

答案 0 :(得分:2)

您可以通过向 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<T['methodOne']>

Playground link