【问题标题】:Typescript extend a class method to an array of methodsTypescript 将类方法扩展为方法数组
【发布时间】:2021-10-10 15:03:20
【问题描述】:

基本思想是我有一个带有方法的抽象类,当被子类扩展时,该方法可以变成方法数组。以下是一个工作示例,但有一些变通方法:

type ClassMethod = (food: string) => void
type ClassMethodArray = ClassMethod[]

abstract class Pet {
  // I would prefer this to be a ClassMethod instead of a ClassMethodArray with 1 entry...
  feed: ClassMethodArray = [
      (food) => console.log(`${food} was tasty!`)
  ]
}

class Cat extends Pet {}

class Dog extends Pet {
  feed: ClassMethodArray = [
      (food) => console.log(`1 ${food} is not enough...`),
      this.feed[0] // ...so that I can omit the [0] here...
  ]
}

// ...and here too
new Cat().feed[0]("cat treat")
new Dog().feed.forEach(func => func("dog treat"))

输出:

"cat treat was tasty!" 
"1 dog treat is not enough..." 
"dog treat was tasty!"

如 cmets 中所述,我希望 Pet 中的抽象方法不是具有 1 个条目的数组,而只是一个 ClassMethod。然后在派生类中,我可以选择让它成为方法或将其扩展为 ClassMethodArray。这有可能吗?

【问题讨论】:

  • 这些类型不兼容。仅通过类型,程序员应该如何知道是否应该直接调用任何给定的 Pet 的 feed 方法或使用 forEach?例如,如果我有一个 Pets 列表并想喂它们所有,我实际上需要知道它们的特定子类,这会破坏实现。
  • @RyanSchaefer 这会起作用,因为我会将它用于接受单个方法或方法数组的快速路由器

标签: javascript typescript class inheritance abstract


【解决方案1】:

如果您希望扩展基类的功能,可以在方法的重写实现中使用super 关键字:

type ClassMethod = (food: string) => void
type ClassMethodArray = ClassMethod[]

abstract class Pet {
  // base implementation
  feed(food: string) {
    console.log(`${food} was tasty!`)
  }
}

class Cat extends Pet {}

class Dog extends Pet {
  feed(food: string) {
    // custom behaviour
    console.log(`1 ${food} is not enough...`)
    // invoking the base implementation
    super.feed(food)
  }
}

new Cat().feed("cat treat")
new Dog().feed("dog treat")

【讨论】:

  • 我特别希望获得一组方法以传递给 Express 路由器中间件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
相关资源
最近更新 更多