Search code examples
typescriptinstanceoftypeof

How to tell the class of an instance


Is there a way of telling what class instance an object is in Typescript? I mean more specifically than just 'Object'.

If you had this:

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

You'd get:

'Object'

Then if you did this:

console.log(x instanceof MyClass);

You'd get:

Uncaught ReferenceError: MyClass is not defined

How can I get it to print out 'MyClass'?


Solution

  • 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.