2017-06-22 65 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); 
}