简体   繁体   English

在 typescript 中使用另一个 class 中的 static class 方法

[英]using static class methods in another class in typescript

I want to use certain static methods from another class in my code, but getting a weird error.我想在我的代码中使用另一个 class 中的某些 static 方法,但出现了一个奇怪的错误。

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()

I created a typescript playground example here我在这里创建了一个 typescript 游乐场示例

So these are the problem lines, where this.mouth is defined to be the class Mouth collapsing the constructor etc code its the same as this:所以这些是问题行,其中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?

If this is confusing I'm wondering what better patterns I could use where I need certain methods to do different things based on the subclass.如果这令人困惑,我想知道我可以使用什么更好的模式,我需要某些方法来根据子类做不同的事情。 But ideally those methods are also available as static methods outside the subclass.但理想情况下,这些方法也可以作为子类外部的 static 方法使用。

You declared your property to be an instance of Mouth您声明您的财产是Mouth的一个实例

mouth: Mouth

... but static methods are not available on instances ...但是 static 方法在实例上不可用

Static methods aren't called on instances of the class. Instead, they're called on the class itself Static 方法不会在 class 的实例上调用。相反,它们会在 class 本身上调用

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

So the soultion is, to set the correct type or let TS do it for you:所以灵魂是,设置正确的类型或让 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')
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM