1

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?

tippexx
  • 65
  • 1
  • 6

1 Answers1

1

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

myArr.forEach(e => {
    if (e instanceof RedElement) {
        ...
    }
});
ancyrweb
  • 1,220
  • 12
  • 12