How to get the class name of an object in TypeScript at runtime?
Hello everyone! I'm new to TypeScript and ran into a problem. I have a class hierarchy, and I need to find out at runtime which specific class an object is an instance of. In regular JavaScript, I would use `obj.constructor.name`, but in TypeScript this doesn't work as I expect.
Here's an example code:
```typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
}
const myPet = new Dog('Rex', 'Labrador');
// Trying to get the class name
console.log(myPet.constructor.name); // This works in JS, but in TS...
```
The problem is that when TypeScript compiles to JavaScri
No answers yet.
Log in to leave an answer
Blogs