Get an object's class name at runtime
Simple answer :
class MyClass {}
const instance = new MyClass();
console.log(instance.constructor.name); // MyClass
console.log(MyClass.name); // MyClass
However: beware that the name will likely be different when using minified code.
My solution was not to rely on the class name. object.constructor.name works in theory. But if you're using TypeScript in something like Ionic, as soon as you go to production it's going to go up in flames because Ionic's production mode minifies the Javascript code. So the classes get named things like "a" and "e."
What I ended up doing was having a typeName class in all my objects that the constructor assigns the class name to. So:
export class Person {
id: number;
name: string;
typeName: string;
constructor() {
typeName = "Person";
}
Yes that wasn't what was asked, really. But using the constructor.name on something that might potentially get minified down the road is just begging for a headache.
I know I'm late to the party, but I find that this works too.
var constructorString: string = this.constructor.toString();
var className: string = constructorString.match(/\w+/g)[1];
Alternatively...
var className: string = this.constructor.toString().match(/\w+/g)[1];
The above code gets the entire constructor code as a string and applies a regex to get all 'words'. The first word should be 'function' and the second word should be the name of the class.
Hope this helps.
See this question.
Since TypeScript is compiled to JavaScript, at runtime you are running JavaScript, so the same rules will apply.