在打字稿中的另一个class中使用静态class方法

using static class methods in another class in typescript

我想在我的代码中使用来自另一个 class 的某些静态方法,但出现奇怪的错误。

class Mouth {
  static greet() {
    console.log('Mouth.greet')
  }
}

class DogMouth extends Mouth {
  static greet() {
    console.log('DogMouth.woof')
  }
}

class Animal {
  mouth: Mouth
  constructor() {
    this.mouth = Mouth
  }

  greet() {
    this.mouth.greet()  // fails with Property 'greet' is a static member of type 'Mouth'
    Mouth.greet() // this works but should be the same thing?
    console.log('Animal.greet')
  }

}

class Dog extends Animal {

  constructor() {
    super()
    this.mouth = DogMouth
  }
}

function main() {
  const pup = new Dog()
  pup.greet()
}

main()

我创建了一个打字稿playground example here

所以这些是问题行,其中 this.mouth 被定义为 class Mouth 折叠构造函数等代码与此相同:

    this.mouth = Mouth
    this.mouth.greet()  // fails with Property 'greet' is a static member of type 'Mouth'
    Mouth.greet() // this works but should be the same thing?

如果这令人困惑,我想知道我可以使用什么更好的模式,我需要某些方法来根据 subclass 做不同的事情。但理想情况下,这些方法也可以作为静态方法使用 outside the subclass.

您已将 属性 声明为 Mouth

的实例
mouth: Mouth

...但是静态方法在实例上不可用

Static methods aren't called on instances of the class. Instead, they're called on the class itself

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

所以解决方案是,设置正确的类型或让 TS 为您完成:

class Animal {
  // TS will detect type from assignment
  mouth = Mouth;

  // Set type manually and assign
  // mouth: typeof Mouth = Mouth;

  // Set type only (and assign later)
  // mouth: typeof Mouth;

  // NOT WHAT YOU WANT (instance, static methods not available)
  // mouth: Mouth = new Mouth();

  greet() {
    this.mouth.greet()
    Mouth.greet()
    console.log('Animal.greet')
  }
}