How do I access a static property in typescript from a subclass instance?

Use case: I have a base class that many other classes inherit from. The base class is called HSManagedObject

.

I have another class called HSContext

that stores a dictionary HSManagedObject

where keys are the names of various subclasses and values ​​are lists of instances of those subclasses. I insert them like this:

insertObject(object: HSManagedObject) { 
   this.projectObjects[object.key()].push(object)
}

      

Since the class names disappear when I minify my javascript (they all become t

), I added a static property for each of the classes key

that uniquely identifies the class in question.

When I add an object to the dictionary, I would like to infer the class name of that object from the instance. Is there a way to get a static variable key

only from an instance when I don't know which subclass it belongs to?

I am currently adding an instance method for each of the subclasses key()

that returns static static key

and calls the instance method to get the class value. It looks like I don't need to do this. So in all my subclasses I have code like this:

static key = "HSRule";
key() {
    return HSRule.key;
}

      

+3


source to share


1 answer


This can be tricky. If TypeScript is compiled before JavaScript, the "classes" become simple variables and the static vars are simply assigned to them. You can try something like this:

Object.getPrototypeOf(object).constructor.key

      



getPrototypeOf () Link

+3


source







All Articles