是否有可能找到从另一个对象派生的对象类型?



我有这样的类

export A {...} export B {...} export C {...}
export type data = A | B | C;

然后我有一个这样的数据数组

dataArr : Array<data> ; 

我是否可以使用type of之类的东西来检查dataArr内部的元素是否为type ofA?或者有其他方法可以达到同样的目的吗?

typeof只适用于原语,所以这是不可能的。您可以使用类型保护来确定某个对象是AB还是C,但请记住,类型保护的复杂性会增加,如果data对象的类型太多,可能会出现问题。

一个简单的类型保护应该是这样的:

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)

在这个例子中(操场在这里),你可以看到我是如何故意省略了myImage的类型。如果你把鼠标悬停在myImage上,你会看到它没有类型,但在我的类型保护检查之后,你可以看到它现在可以识别出对象是这个特定的类型。当你的问题中有多种类型时,你可以在这里做各种链接,尽管这可能会导致混乱的情况或难以阅读的代码,这取决于你如何组织检查。

您可以添加鉴别属性到每个类型,然后根据该属性检查元素的类型。我假设A,BC是这样的:

interface A  {
name: string; 
age: number;
kind: "A"
};
interface B  {
city: string; 
state: string;
kind: "B"
};
interface C  {
address: string;
kind: "C"
};

这里,kind是一个判别属性,表示接口的类型。在switch-case中,您可以获得以下类型:

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;
}
});

如果A,BC是class:

class A  {
name: string; 
age: number;
};
class B  {
city: string; 
state: string;
};
class C  {
address: string;
}; 

可以使用instanceof关键字:

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
}
});

最新更新