【发布时间】: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 类的返回类型?
【问题讨论】:
标签: typescript typescript-generics