In .NET, getting the class name of an object is straightforward using obj.GetType().Name. In JavaScript, this approach does not apply: typeof obj returns "object" or another primitive type string, never the class name. However, you can still retrieve a class name in JavaScript.
In ES6, you can use Function.name to get the name of a function (documentation).
JavaScript
function test() { }
console.log(test.name); // print "test"
In JavaScript, a class is a function, so you can retrieve its name using the name property:
TypeScript
class Sample { }
console.log(Sample.name); // print "Sample"
For a class instance, use the constructor property to access the constructor function. You can then get the class name from the constructor's name property:
TypeScript
const obj = new Sample();
console.log(obj.constructor.name); // print "Sample"
Note 1: If you minify your scripts, some functions and classes may be renamed, so the class name will reflect the minified name rather than the original one from your source. UglifyJS provides an option to preserve specific names: uglifyjs ... -m reserved=['$', 'Sample']
Note 2: This does not work if the class contains a method named name. In that case, the name property is not automatically set, so the class name cannot be retrieved this way. You can read the specification for details on this behavior.
Note 3: TypeScript does not show constructor in auto-completion, but it is fully supported and typed.
Do you have a question or a suggestion about this post? Contact me!