【问题标题】:How do I get the static variables from the class(es) of an object in TypeScript?如何从 TypeScript 中对象的类中获取静态变量?
【发布时间】: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


    【解决方案1】:

    给定一个对象实例,你可以沿着原型链向上走:

    function describe(animal: Animal) {
        for (let prototype = Object.getPrototypeOf(animal); prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype))
            console.log(prototype.constructor.description);        
    }
    

    playground

    【讨论】:

    • 美丽。谢谢!
    猜你喜欢
    • 2019-12-01
    • 2020-01-12
    • 2012-02-04
    • 2021-03-23
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2012-08-30
    相关资源
    最近更新 更多