识别数组元素的特定 class?

Identify specific class of array element?

我有一个包含不同实现的数组 (Element[])。

现在,识别数组元素的“subclass”/类型的正确方法是什么? 即如何将 Element[1] 识别为 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(...),
...
]

现在,当我稍后想要使用其中一个元素时,我需要知道它是哪个 type/class,但我剩下的只是一个类型为 Element 的对象。

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

我显然可以添加一个 属性,通过字符串或枚举将每个元素标识为其特定 class,但这似乎不太优雅。

有没有更好的方法?

由于您正在创建 类,因此您可以使用 instanceof 运算符来区分不同的元素。

myArr.forEach(e => {
    if (e instanceof RedElement) {
        ...
    }
});