Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: get to get Class name at runtime? [duplicate]

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

like image 568
Zach Avatar asked Apr 01 '14 05:04

Zach


1 Answers

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.

like image 136
Rahul Tripathi Avatar answered Sep 19 '22 22:09

Rahul Tripathi