在 TypeScript 中获取对象的类名

在 TypeScript 中获取对象的类名

Get the Class Name of an Object in TypeScript

使用name对象的构造函数上的属性来获取对象的类名,例如const className = e1.constructor.name. constructor
属性返回对创建该对象的构造函数的引用。

索引.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

我们访问了Object.constructorname属性上的

属性。

Object.constructor属性返回对构造函数的引用,从中创建对象。

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

您还可以使用运算符验证该constructor属性是否指向正确的类instanceof

索引.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.

在这种情况下要考虑的另一种方法是在类上定义一个属性并将其设置为特定名称。

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

现在您可以使用该className属性获取对象类的名称,它可能不会受到缩小过程的影响。