[英]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.