泛型方法用多态覆盖

时间:2019-07-27 19:56:22

标签: typescript generics

我想这样做:

class A {
  static a: string = '';
  static m<T extends typeof A>(this: T) {
    this.a;
  }
}
class B extends A {
  static b: number = 5;
  static m<T extends typeof B>(this: T) {
    this.b + this.a;
  }
}

但这会导致此错误:

Class static side 'typeof B' incorrectly extends base class static side 'typeof A'.
  Types of property 'm' are incompatible.
    Type '<T extends typeof B>(this: T) => void' is not assignable to type '<T extends typeof A>(this: T) => void'.
      The 'this' types of each signature are incompatible.
        Type 'T' is not assignable to type 'typeof B'.
          Property 'b' is missing in type 'typeof A' but required in type 'typeof B'.ts(2417)

这对我来说没有意义,因为清楚地调用B.m()将发送B类型。此外,B是专业化的,因此它应该满足A的全部要求,对吧?

当然可以将其更改为

class B extends A {
  static b: number = 5;
  static m<T extends typeof A>(this: T) {
    this.b + this.a;
  }
}

导致this.b出错。

我可以通过以下方法解决此问题:

class B extends A {
  static b: number = 5;
  static m<T extends typeof A>(this: T & typeof B) {
    this.b + this.a;
  }
}

但这似乎非常冗长,我不想强​​迫我的图书馆用户变得如此冗长,并记住这些奇怪的事情。

我想念什么吗?这是错误吗?有更好的解决方案吗?

0 个答案:

没有答案
相关问题