[英]Typescript generics. Can't pass instance of B to a argument a: T where T extends B. Why?
I have class: 我有课:
class X<T extends B> [...]
// this.p.a :: B | null
methodA(a: T):void {[...]}
methodB(): void {
if(this.p.a){ // :: B
this.methodA(this.p.a) // Error
As you can see, I'm relaying on T
being any type as long as it extends B
, and then I'm passing some property to it of said type B
. 正如你所看到的,我在转播
T
是任何类型,只要它延伸B
,然后我通过一些属性,以它说类型的B
。 However Typescript can't infer that B
is a type that satisfy T
type parameter in the last line of above code snippet. 但是,Typescript无法推断出
B
是在上述代码段的最后一行中满足T
type参数的类型。
Error message: 错误信息:
error TS2345: Argument of type 'B' is not assignable to parameter of type 'T'.
Why is this not working? 为什么这不起作用? Should I change any offending type declaration to
B
instead of T
and relay on inheritance? 我应该将任何令人讨厌的类型声明更改为
B
而不是T
并继承吗?
You're getting an error because someone might use X<T>
where T
is a subclass of B
, and then this.pa
might be a B
that is not a T
. 您遇到了错误,因为有人可能使用
X<T>
,其中T
是B
的子类,然后this.pa
可能是不是T
的B
To know the best way to resolve the error, we'd need to know more about what you are trying to achieve. 要知道解决错误的最佳方法,我们需要更多地了解您要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.