Home > OS >  How do I get the static variables from the class(es) of an object in TypeScript?
How do I get the static variables from the class(es) of an object in TypeScript?

Time:12-02

I would like to access the static members of classes from which an object was created including parent classes from which the constructor was extended.

My current work around is to add each class to an array in the constructor, however, I would much prefer a more elegant solution if one exists as I am defining thousands of classes, or a way to restrict the Type to the master class.

Here is some example code to show what I mean.

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)
}

I would prefer classes to only accept Animal and classes that extend Animal.

CodePudding user response:

You can walk up the prototype chain given an object instance:

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

playground

  • Related