I have classes that looks like this.
export A {...} export B {...} export C {...}
export type data = A | B | C;
Then I have an array of data like this.
dataArr : Array<data> ;
Is it possible that I use something like type of
to check whether or not the element inside dataArr
is type of
A
? or any other way to achieve the same goal?
CodePudding user response:
typeof
only works on primitives so that wouldn't be possible. You could use a type guard to determine whether something is A
, B
, or C
but keep in mind the complexity of the type guard(s) will grow and may be problematic if you have too many types for the data
object.
A simple type guard would look like this:
interface ImageTypeA {
data: string
width: number
height: number
}
const isImageTypeA = (object: any): object is ImageTypeA => {
return !!object.data
}
const myImage = {
data: 'A',
width: 1,
height: 1
}
console.log(isImageTypeA(myImage) && myImage.data)
In this example (playground here) you can see how I've purposefully left out the type on myImage
. If you hover over myImage
you'll see it doesn't have a type, but after my type guard check you can see that it now does recognize that the object is this specific type. You can do various chaining here when there are multiple types like in your question though it can lead to confusing situations or hard to read code depending on how you structure the checks.
CodePudding user response:
You can add a discriminant property to each type, and then check the type of the elements by that property. I assume A
, B
and C
are like this:
interface A {
name: string;
age: number;
kind: "A"
};
interface B {
city: string;
state: string;
kind: "B"
};
interface C {
address: string;
kind: "C"
};
Here, kind
is a discriminant property, which shows the type of interface. In a switch-case
you can get the types:
type data = A | B | C;
const dataArr: Array<data> = *value that you want to assign*;
dataArr.forEach(item => {
switch (item.kind) {
case 'A':
//item type is A
break;
case 'B':
//item type is B
break;
case 'C':
//item type is C
break;
}
});
If A
, B
and C
are class:
class A {
name: string;
age: number;
};
class B {
city: string;
state: string;
};
class C {
address: string;
};
You can use instanceof
keyword :
dataArr.forEach(item => {
if(item instanceof A){
//item type is A
}
if(item instanceof B){
//item type is B
}
if(item instanceof C){
//item type is C
}
});