Get the Class Name of an Object in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 17, 2022

banner

Photo from Unsplash

Get the Class Name of an Object in TypeScript #

Use the name property on an object's constructor to get the class name of the object, e.g. const className = e1.constructor.name. The constructor property returns a reference to the constructor function that created the object.

index.ts
class Employee {} const e1 = new Employee(); console.log(e1.constructor.name); // 👉️ "Employee" console.log(Employee.name); // 👉️ "Employee" console.log(e1.constructor.name === Employee.name); // 👉️ true

We accessed the name property on the Object.constructor property.

The Object.constructor property returns a reference to the constructor function, from which the object was created.

index.ts
class Employee {} // 👇️ const e1: Employee const e1 = new Employee(); // 👇️ const cls: Function const cls = e1.constructor; console.log(cls); // 👉️ Employee

You can also verify that the constructor property points to the correct class, by using the instanceof operator.

index.ts
class Employee {} // 👇️ const e1: Employee const e1 = new Employee(); console.log(e1 instanceof e1.constructor); // 👉️ true

The instanceof operator checks if the value on the right hand side appears in the prototype of the value on the left hand side.

An alternative approach to get the class name of an object is to create a method on the class.

index.ts
class Employee { getClassName() { return this.constructor.name; } } // 👇️ const e1: Employee const e1 = new Employee(); // 👇️ const className: string const className = e1.getClassName(); console.log(className); // 👉️ Employee

This approach is useful when you need to access the constructor.name property often, as the abstraction makes your code more readable.

Note that all objects (other than ones created using Object.create(null)) have a constructor property.

Objects that are created without a constructor function have a constructor property that points to the main Object constructor for the specific type.

index.ts
console.log({}.constructor.name); // 👉️ Object console.log([].constructor.name); // 👉️ Array

It should be noted that if you minify your code in production, the class name might change, e.g. to something like e or b.

One alternative approach to consider in this situation is to define a property on the class and set it to the specific name.

index.ts
class Employee { className = 'Employee'; } // 👇️ const e1: Employee const e1 = new Employee(); // 👇️ const className: string const className = e1.className; console.log(className); // 👉️ "Employee"

Now you can use the className property to get the name of the class of the object and it likely won't be affected by your minification process.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.