【发布时间】: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