Sometimes, we want to get an object’s class name at runtime with TypeScript.
In this article, we’ll look at how to get an object’s class name at runtime with TypeScript.
How to get an object’s class name at runtime with TypeScript?
To get an object’s class name at runtime with TypeScript, we canm use the name property of the constructor or class.
For instance, we write
class MyClass {}
const x = new MyClass();
console.log(x.constructor.name);
console.log(MyClass.name);
to get the name property from a MyClass instance with x.constructor.name.
Likewise, we get the class name from the static MyClass.name property.
They should both return 'MyClass'.
Conclusion
To get an object’s class name at runtime with TypeScript, we canm use the name property of the constructor or class.
