5

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 HSManagedObjects 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 become 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;
}

1 Answer 1

7

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

Object.getPrototypeOf(object).constructor.key

getPrototypeOf() Reference

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This works perfectly, it would be awesome if typescript supported it natively, but in the meantime this is a great workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.