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?

2
  • You could use (GreenElement | RedElement)[] and check then if(el instanceof GreenElement) etc Commented May 31, 2022 at 11:06
  • instanceof did not work for me due to an incorrect import... now works like a charm Commented May 31, 2022 at 11:18

1 Answer 1

1

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

myArr.forEach(e => {
    if (e instanceof RedElement) {
        ...
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.