我无法推断类泛型属性的返回类型。
我有一个有效的简单设置:
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}
有没有办法获取子类的返回类型?
答案 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']>
。