Get the name of a TypeScript class at runtime

 
 
  • Gérald Barré

in .NET, it's easy to get the class name of an object using obj.GetType().Name. In JavaScript, this doesn't work: typeof obj return "object" or something else, but never the name of the class. This doesn't mean you cannot get the name of a class in JS.

In ES6, you can use Function.name to get the name of a function (documentation).

JavaScript
function test() { }
console.log(test.name); // print "test"

Well, in JavaScript, a class is a function! So, you can get its name using the name property:

TypeScript
class Sample { }
console.log(Sample.name); // print "Sample"

For an instance of a class, you can use the constructor property to get the constructor function: obj.constructor. This way you can get the name of the class by getting the name of the constructor function:

TypeScript
const obj = new Sample();
console.log(obj.constructor.name); // print "Sample"

Note 1: If you minify your scripts, some functions/classes may be renamed. So, the name of the class won't be the original name (I mean the name from your original source file), but the name after minification. UglifyJS has an option to not mangle some names uglifyjs ... -m reserved=['$', 'Sample']

Note 2: This doesn't work if the class contains a method named name. In this case, the browser won't automatically add the name property, so you won't be able to get the name of the class. You can read the specification about this behavior.

Note 3: TypeScript doesn't show constructor in the auto-completion. However, this is supported and typed.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub