2017-06-22 69 views
0

有一个question on SO关于创建一个不同类型的数组,但我想创建一个具有多种复杂类型的数组。在链接到问题的答案建议使用联合类型,但我不认为这将足以满足一个复杂的类型,如typescript documentation一个具有多种复杂类型的数组

If we have a value that has a union type, we can only access members that are common to all types in the union. 

我想创建报表的数组。然而,一些报告具有不同的属性,也有几个共同点。我担心,如果我在下面创建它,然后在代码中的某处,我可能无法访问子报表上的不同属性。

在Typescript中创建一个复杂类型数组的建议方法是什么?

interface Reports extends Array<Report>{} 

interface Report { 
    id: number; 
    timestamp: number; 
    type: string; 
    subreport: SubReportA | SubReportB | SubReportC 
} 



interface SubReportA { 
values: [] 
} 
interface SubReportB { 
random_property: number; 
other_random_name: number; 
} 
interface SubReportC{ 
values: []; 
name: string; 
} 
+0

不应该'SubReportA'等等'SubReport'的子类,然后你只是'subreport:Subreport'? – 2017-06-22 17:11:39

+0

你可以举一个例子说明你想如何使用你的数组? – Rodris

+0

@RodrigoPedrosa将其映射到它上面,并将每个成员都呈现在列表中的Report组件中。 – Leahcim

回答

2

这将是一个用例discriminated unions。首先,我们需要一个用于各种子报告的基础接口。我还将添加一个区分字段kind,它只能假定在编译时间“A”,“B”和“C”中已知的特定值。

interface SubReport { 
    kind: "A" | "B" | "C"; 
} 

在这一点上,我们可以使我们的接口指定一个字符串字面每个:

interface SubReportA { 
    kind: "A"; 
    values: [] 
} 

interface SubReportB { 
    kind: "B"; 
    random_property: number; 
    other_random_name: number; 
} 

interface SubReportC{ 
    kind: "C"; 
    values: []; 
    name: string; 
} 

同样的道理可以如果需要的话可以应用于原始Report型。我不确定报告的“类型”字段是否应该作为鉴别器,但如果它是可移动到子报告对象的话。

此外,正如上面的链接所述,区分的联合允许您在鉴别器上测试后检索特定的字段。

if (subreport.kind === 'B') { 
    console.log(subreport.random_property); 
}