5

In C#, it's easy to get the class name at runtime using Reflection. Is it possible in TypeScript?

wonea
  • 4,783
  • 17
  • 86
  • 139
Zach
  • 5,715
  • 12
  • 47
  • 62

1 Answers1

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