【问题标题】:using static class methods in another class in typescript在打字稿的另一个类中使用静态类方法
【发布时间】:2020-10-08 14:18:36
【问题描述】:

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

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 被定义为类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?

如果这令人困惑,我想知道我可以使用哪些更好的模式,我需要某些方法来根据子类做不同的事情。但理想情况下,这些方法也可用作子类外部的静态方法。

【问题讨论】:

  • Mouth 是实例的类型。课程本身是typeof Mouth。即你需要说:mouth: typeof Mouth

标签: javascript typescript static subclass


【解决方案1】:

您将您的属性声明为Mouth 的实例

mouth: Mouth

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

类的实例不会调用静态方法。相反,它们是在类本身上调用的

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')
  }
}

【讨论】:

  • 知道了,谢谢! mouth: Mouth 是 Mouth 实例的设置,而不是 Mouth 类本身。 mouth = Mouth 进行分配并让 TS 处理类型。
  • 我添加了更多的 cmets 使其在代码中更加明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多