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

70
Views
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 answers
Answer question

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 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!