zacaj
zacaj

Reputation: 2065

(Typescript) compare types of two objects

I have an abstract base class with many different child classes extending it. If given two instances of the class, is it possible to check if they have the same child type?

I wanted to do something like this, but typeof just returns "object" so it's pretty useless

compare(a: Parent, b: Parent): boolean {
    return typeof a === typeof b
}

Upvotes: 0

Views: 2908

Answers (1)

Paleo
Paleo

Reputation: 23672

Maybe by comparing the constructor property:

compare(a: Parent, b: Parent): boolean {
    return a.constructor === b.constructor
}

But it isn't a rock-solid solution because the property constructor can be reassigned:

The following example shows how to modify constructor value of generic objects. Only true, 1 and "test" will not be affected as they have read-only native constructors. This example shows that it is not always safe to rely on the constructor property of an object. […]

Upvotes: 2

Related Questions