To categorize each type, you can introduce a unique property called the discriminant property, and then differentiate the types of elements based on that property. Let's assume the structures of A
, B
, and C
are defined as follows:
interface A {
name: string;
age: number;
kind: "A"
};
interface B {
city: string;
state: string;
kind: "B"
};
interface C {
address: string;
kind: "C"
};
In this setup, the kind
serves as the discriminant property indicating the interface type. By utilizing a switch-case
statement, you can identify the different types:
type data = A | B | C;
const dataArr: Array<data> = *insert desired values here*;
dataArr.forEach(item => {
switch (item.kind) {
case 'A':
//item is of type A
break;
case 'B':
//item is of type B
break;
case 'C':
//item is of type C
break;
}
});
If A
, B
, and C
are represented as classes:
class A {
name: string;
age: number;
};
class B {
city: string;
state: string;
};
class C {
address: string;
};
You can utilize the instanceof
keyword like so:
dataArr.forEach(item => {
if(item instanceof A){
//item is an instance of A
}
if(item instanceof B){
//item is an instance of B
}
if(item instanceof C){
//item is an instance of C
}
});