Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a static version of `instanceof`?

Is there a static equivalent of instanceof? I.E., rather than:
obj1 instanceof Type
something like:
TypeA instanceof TypeB?

I couldn’t find anything on the matter, so I hacked together this:

function InstanceOf(type,parent) {
    do{ if(type === parent) return true;}
    while(type = Object.getPrototypeOf(type));
    return false;
}
//...
Instanceof(ChildClass, ParentClass); // = boolean

But I feel like there’s a better/more native way to do this, but again, can’t find anything on it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a better/standard way do check static class inheritance? Or is my hack about the best it’s gonna get?

>Solution :

You can use isPrototypeOf.

class A {}
class B extends A {}
class C extends B {}
const InstanceOf = (type, parent) => type === parent || parent.prototype.isPrototypeOf(type.prototype);
console.log(InstanceOf(B, A));
console.log(InstanceOf(A, A));
console.log(InstanceOf(C, A));
console.log(InstanceOf(C, B));
console.log(InstanceOf(B, C));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading