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

78
Visualizações
Identify specific class of array element?

I have an array (Element[]) that contains different implementations.

Now, what's the proper way to identify the "subclass"/type of an array element? i.e. how do I identify Element[1] as an implementation of RedElement?

export interface Element {
   ...
}
export class RedElement implements Element {
    ...specific functionality/values.
}

export class GreenElement implements Element {
    ...specific functionality/values.
}
const myArr: Element[] = [
    new GreenElement(...params),
    new GreenElement(...otherParams),
    new RedElement(...),
...
]

Now when I later want to work with one of those elements I need to know which type/class it is, but all I'm left with is an Object of type Element.

myArr.forEach(e => {
    e <- has type Element
});

I could obviously add a property that identifies each element as its specific class by a string or enum but that seems not too elegant.

Is there a better way?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since you are creating classes, you can use instanceof operator to discriminate between your different elements.

myArr.forEach(e => {
    if (e instanceof RedElement) {
        ...
    }
});
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