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?