如何分辨实例的类

时间:2019-03-05 16:15:14

标签: typescript instanceof typeof

有没有办法告诉对象Typescript中对象的类实例?我的意思不仅仅是“对象”。

如果您有这个:

const x : MyClass = new MyClass();
console.log(typeof(x));

您会得到:

'Object'

然后,如果您这样做:

console.log(x instanceof MyClass);

您会得到:

Uncaught ReferenceError: MyClass is not defined

如何获取它以打印出“ MyClass”?

1 个答案:

答案 0 :(得分:0)

You can use x.constructor.name.

The .constructor property of an object holds a reference to the constructor function that created the instance (the class function) and the .name property of a Function keeps its name.

This is JavaScript, TypeScript is not involved. TypeScript types doesn't help here, they vanish on the compilation to JavaScript code.