[英]using static class methods in another class in typescript
我想在我的代码中使用另一个 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()
所以这些是问题行,其中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?
如果这令人困惑,我想知道我可以使用什么更好的模式,我需要某些方法来根据子类做不同的事情。 但理想情况下,这些方法也可以作为子类外部的 static 方法使用。
您声明您的财产是Mouth
的一个实例
mouth: Mouth
...但是 static 方法在实例上不可用
Static 方法不会在 class 的实例上调用。相反,它们会在 class 本身上调用
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')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.