【问题标题】:TypeScript - get the declaring type from a static methodTypeScript - 从静态方法中获取声明类型
【发布时间】: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 {

}

分别在AnimalDogCat 上调用getType(),应该会产生:

Animal.getType() // Animal
Dog.getType() // Dog
Cat.getType() // Cat

我什至不确定这是否可能,但如果有人能指出我正确的方向,那就太好了!

附带说明 - 我想要做的是使用 getType() 返回声明类型,以便我可以迭代该类型的其他静态成员,基本上相当于

Object.keys(Dog) // ["Poodle", "Labrador", "Husky"]

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我自己找到的...

    static getType(): any {
        return Object
            .create(this.prototype)
            .constructor;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 2014-11-09
      • 2020-07-12
      • 2013-01-10
      • 2017-06-27
      • 2023-03-07
      • 2014-10-17
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多