4

How can I determine if two objects are of the same type (ie the same class)? The objects can be any of about 20 different classes so I don't want a giant test going, both instanceof A, both instanceof B, ... But there's no GetType()/getClass() in typescript.

thanks - dave

2 Answers 2

7

Just use the constructor property. Reference : http://basarat.github.io/this-and-prototype/#/reflection

class Animal {}
class Bird extends Animal {}


var animal = new Animal();
var bird = new Bird();

console.log(animal.constructor == Animal); // true 
console.log(bird.constructor == Bird); // true
Sign up to request clarification or add additional context in comments.

Comments

5

I don't know typescript, but this is returning true:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

var a = new Greeter("a");
var b = new Greeter("b");

alert(a.constructor === b.constructor);

Just ran it here http://www.typescriptlang.org/Playground

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.