Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda