![](/img/trans.png)
[英]How to infer the generic return type that is bound to a generic parameter of a parameterized class in a typescript method?
[英]Infer class generic property method return type
我无法推断 class 泛型属性的返回类型。
我有一个有效的简单设置:
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
class 的子代,则 TS 不会将返回类型更新为B
子代 class 方法。
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}
有没有办法获得子class 的返回类型?
您可以通过向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']>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.