0

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'?

gib65
  • 1,709
  • 3
  • 24
  • 58
  • Possible duplicate of [Get the name of an object's type](https://stackoverflow.com/questions/332422/get-the-name-of-an-objects-type) – Madhawa Priyashantha Mar 05 '19 at 16:16
  • It doesn't help to know the instance type in TypeScript. In order to `console.log()` it you have to be able to find out the class name in JavaScript, at the run time. – axiac Mar 05 '19 at 16:35

1 Answers1

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.

axiac
  • 68,258
  • 9
  • 99
  • 134