【发布时间】:2021-12-01 16:37:25
【问题描述】:
我想访问创建对象的类的静态成员,包括扩展构造函数的父类。
我目前的工作是将每个类添加到构造函数中的数组中,但是,如果存在一个更优雅的解决方案,因为我正在定义数千个类,或者一种将类型限制为主的方法类。
这里有一些示例代码来说明我的意思。
type Class = { new(...args: any[]): any; }
class Animal {
static description = "A natural being that is not a person"
classes : Class[] = []
constructor() {
this.classes.push(Animal)
}
}
class Mammal extends Animal {
static description = "has live births and milk"
constructor() {
super() // adds Animal to classes
this.classes.push(Mammal)
}
}
class Dog extends Mammal {
static description = "A man's best friend"
constructor() {
super() //adds Animal and Mammal to classes
this.classes.push(Dog)
}
}
class Cat extends Mammal {
static description = "A furry purry companion"
constructor() {
super() //adds Animal and Mammal to classes
this.classes.push(Cat)
}
}
let fido = new Dog()
fido.classes.forEach(function(i) {
console.log(i.description)
}
我希望类只接受 Animal 和扩展 Animal 的类。
【问题讨论】:
标签: typescript class inheritance static