Categories
TypeScript Answers

How to get an object’s class name at runtime with TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *