In JavaScript, inheritance is achieved by creating the prototype from the constructor of the superclass.
For example, consider the following classes:
class A { }
class B extends A { }
class C extends B { }
You can determine subclass relationships using the .prototype
property:
console.log(A.prototype instanceof Object);
console.log(B.prototype instanceof Object);
console.log(B.prototype instanceof A);
console.log(C.prototype instanceof A);
console.log(C.prototype instanceof B);
console.log(C.prototype instanceof C); // false
The first five checks return true
, except for the last one.
To create a function that checks if one class is a subclass or the same class as another, you can do this:
declare type Class = new (...args: any[]) => any;
function isSubClassOf(cls: Class, superCls: Class): boolean {
return cls === superCls || cls.prototype instanceof superCls;
}
The following checks all return true
, except the last one:
console.log(isSubClassOf(C, A));
console.log(isSubClassOf(C, B));
console.log(isSubClassOf(C, C));
console.log(isSubClassOf(B, A));
console.log(isSubClassOf(A, A));
console.log(isSubClassOf(A, C)); // false
You can use this function in your code like so:
if (list.findIndex((item) => isSubClassOf(element, item)) === -1) {
list.push(element);
}