Check if a class is a super-class of another class

Viewed 139

I have an array of classes (not objects). I need only to add new classes to the array only if there is no sub-class is not there. But this code doesn't work this these are not initiated objects.


import {A} from './a';
import {B} from './b';

import {otherList} from './list';


export const getList =()=>{
  const list = [A,B];
  
  otherList.forEach((element) => {
    if (list.findIndex((item) => element instanceof item) === -1) {
      list.push(element);
    }
  });
  return list;
}

1 Answers

JavaScript inheritance works by having the prototype be created from the super class constructor.

This means if you have something like this:

class A { }
class B extends A { }
class C extends B { }

then you can check for a subclass with .prototype:

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

These all log true except the last.

Based on that you can build this function to check if one class is a sub class or the same class as the other:

declare type Class = new (...args: any[]) => any;
function isSubClassOf(cls: Class, superCls: Class): boolean {
    return cls === superCls || cls.prototype instanceof superCls;
}

These all log true except the last:

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

In your case you can then use the function like this:

if (list.findIndex((item) => isSubClassOf(element, item)) === -1) {
   list.push(element);
}
Related