如何解决在打字稿中的另一个类中使用静态类方法
我想在我的代码中使用另一个类中的某些静态方法,但出现一个奇怪的错误。
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
的实例
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')
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。