Use case:
I have a base class from which many other classes inherit.
The base class is called HSManagedObject
.
I have another class called HSContext
that keeps a dictionary of HSManagedObject
s where the keys are the names of the various subclasses and the values are lists of the instances of those subclasses. I insert them like so:
insertObject(object: HSManagedObject) {
this.projectObjects[object.key()].push(object)
}
Because class names go away when I minify my javascript (they all bee t
), I added a static property to each of those classes called 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 the static key
variable just from the instance when I don't know which subclass it belongs to?
Currently I am adding an instance method to each of the subclasses called key()
that returns the class's static key
value and calling the instance method to get the class value. It seems like I shouldn't need to do this though. So in all of my subclasses I have some code like this:
static key = "HSRule";
key() {
return HSRule.key;
}
Use case:
I have a base class from which many other classes inherit.
The base class is called HSManagedObject
.
I have another class called HSContext
that keeps a dictionary of HSManagedObject
s where the keys are the names of the various subclasses and the values are lists of the instances of those subclasses. I insert them like so:
insertObject(object: HSManagedObject) {
this.projectObjects[object.key()].push(object)
}
Because class names go away when I minify my javascript (they all bee t
), I added a static property to each of those classes called 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 the static key
variable just from the instance when I don't know which subclass it belongs to?
Currently I am adding an instance method to each of the subclasses called key()
that returns the class's static key
value and calling the instance method to get the class value. It seems like I shouldn't need to do this though. So in all of my subclasses I have some code like this:
static key = "HSRule";
key() {
return HSRule.key;
}
Share
Improve this question
asked Aug 5, 2015 at 14:37
Samantha JohnSamantha John
9781 gold badge8 silver badges18 bronze badges
1 Answer
Reset to default 7This may be tricky. If TypeScript is piled down to JavaScript, the "classes" bee simple variables and the static vars are just assigned to them. You could try something like this:
Object.getPrototypeOf(object).constructor.key
getPrototypeOf() Reference