【发布时间】:2018-04-06 21:13:56
【问题描述】:
我正在尝试研究如何返回声明静态方法的类型。这也应该适用于派生类型。
class Animal {
static getType(): any {
// Here I want to return the type that declares this method,
// In this case Animal.
// For derived types, it should return i.e. Dog, Cat, etc.
// I tried...
// return this.prototype; // But this doesn't work.
}
}
class Dog extends Animal {
}
class Cat extends Animal {
}
分别在Animal、Dog 和Cat 上调用getType(),应该会产生:
Animal.getType() // Animal
Dog.getType() // Dog
Cat.getType() // Cat
我什至不确定这是否可能,但如果有人能指出我正确的方向,那就太好了!
附带说明 - 我想要做的是使用 getType() 返回声明类型,以便我可以迭代该类型的其他静态成员,基本上相当于
Object.keys(Dog) // ["Poodle", "Labrador", "Husky"]
【问题讨论】:
标签: typescript