2017-06-22 11 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'があるだけですか? –

+0

配列の使い方の例を挙げることはできますか? – Rodris

+0

@RodrigoPedrosaはその上にマップし、リスト内のReportコンポーネントの各メンバーをレンダリングします。 – Leahcim

答えて

2

これはdiscriminated unionsの使用例です。まず、すべての種類のサブレポート用の基本インターフェースが必要です。また、コンパイル時に "A"、 "B"、 "C"という特定の値しか想定できない識別フィールドkindを追加します。この時点で

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

、私たちは私たちのインターフェースは、各リテラルの1つの文字列を指定することができます:

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

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

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

必要であれば、同じ論法は、元Reportタイプにも適用することができます。私は、レポートの "タイプ"フィールドが弁別器であるはずなのかどうかはわかりませんが、それがあればサブレポートオブジェクトに移動できます。

また、上記のリンクで説明したように、識別された共用体を使用すると、一度ディスクリミネータでテストすると特定のフィールドを取得できます。

関連する問題