相关疑难解决方法(0)

引用没有名称的类以在 TypeScript 的子类中使用不同的静态方法

在 ES6 中,您可以通过this.constructor以下方式引用静态方法:

class MainClass {
  static info() {
    return "This is some information";
  }
  constructor() {
    this.info = this.constructor.info(); // Allows subclass to define different '.info()' method.
  }
}

class ChildClass extends MainClass {
  static info() {
    return "This information is from the child";
  }

  constructor() {
    super();
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在 TypeScript 中做到这一点?我希望能够覆盖超类的静态方法并从子类中使用它,而无需在实例方法中重新定义引用。现在,我知道如何在 TypeScript 中访问静态方法的唯一方法是使用类名。

MainClass.info();
Run Code Online (Sandbox Code Playgroud)

但是如果我这样做,子类将继续使用MainClass.info();而不是它自己的.info()方法。

typescript typescript1.8

7
推荐指数
2
解决办法
2086
查看次数

标签 统计

typescript ×1

typescript1.8 ×1