Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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;
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!