Reputation: 2065
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
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 theconstructor
property of an object. […]
Upvotes: 2