简体   繁体   English

打字稿泛型。 无法将B的实例传递给参数a:T,其中T扩展了B。为什么?

[英]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> ,其中TB的子类,然后this.pa可能是不是TB 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.

相关问题 打字稿:无法让泛型与扩展一起使用 - Typescript: can't get generics to work with extends 为什么 `T extends B` 不能在将来的引用中将 T 限制为 B? - Why doesn't `T extends B` work to limit T to B in future references? TypeScript:具有泛型的递归深度可变。 错误:T 不可分配给 Mutable<T> - TypeScript: Recursive Deep Mutable with Generics. Error: T is not assignable to Mutable<T> TypeScript:为什么我不能分配类型为 { a: “a”, b: “b” } 的对象的有效字段 - TypeScript: Why can't I assign a valid field of an object with type { a: “a”, b: “b” } 泛型:TS2345类型“ T [keyof T]”的参数不能分配给类型“ Date”的参数,其中<T extends {}> - Generics: TS2345 Argument of type 'T[keyof T]' is not assignable to parameter of type 'Date' where <T extends {}> Typescript 接口 Generics:仅当 T 属于联合类型 'A | 时才允许泛型 T 乙' - Typescript interface Generics : Allow generic T only if T is of union type 'A | B' TypeScript Generics 问题:类型 T(扩展类型)不可分配给 T - TypeScript Generics problem: type T (extends Type) is not assignable to T 无法在打字稿函数中传递参数 - can't pass an argument in a typescript function 打字稿中的泛型-未定义T - Generics in Typescript - Undefined T TypeScript 无法解析函数泛型中的元组 - TypeScript can't resolve tuple in function generics
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM