In C#, it's easy to get the class name at runtime using Reflection. Is it possible in TypeScript?
Asked
Active
Viewed 1.3k times
1 Answers
7
At runtime you are running JavaScript. So you can check this answer for details.
Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can't speak for other implementations.

Community
- 1
- 1

Rahul Tripathi
- 168,305
- 31
- 280
- 331