I want to use certain static methods from another class in my code, but getting a weird error.
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
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 = 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.
Mouthis the type of the instances. The class itself istypeof Mouth. i.e. you need to say:mouth: typeof Mouth