簡體   English   中英

在 typescript 中使用另一個 class 中的 static class 方法

[英]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()

我在這里創建了一個 typescript 游樂場示例

所以這些是問題行,其中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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM