2017-09-14 3 views
0

私が話しているバックエンドには、注文を作成するためのAPIがあります。 このような注文には、クライアントが受け取ったときにIDで指定され、サーバーから送信されたときに完全な詳細なオブジェクトである製品があります。私は明示的なキャストなしに、オブジェクトとして製品を数値として製品を使用または受信していたときにtypescriptですインタプリタは理解するであろう場合、それは完璧になるシームレスな方法でtypescriptユニオンを使用する

export interface Order { 
    userId: number; 
    bought_products: BoughtProduct[]; 
} 

export interface BoughtProduct { 
    quantity: number; 
    product: number | Product; // not specified here 
    created?: string; // other keys are optional because only present if sent by Backend 
} 

typescriptですインターフェイスは、このようなものになるだろう。
これは、ネストされた配列なので、キャストを使用すると複雑になるからです。

問題のより直接的な例はthis playground link

+0

あなたがここに二つの異なるタイプがあり、おそらく別の2を持っている必要がありますように私には聞こえ:その後、私はuser defined type guardsを使用したい

interface Order { userId: number; bought_products: Array<ClientBoughtProduct | ServerBoughtProduct>; } interface BoughtProduct<T> { quantity: number; product: T; } interface ClientBoughtProduct extends BoughtProduct<number> {} interface ServerBoughtProduct extends BoughtProduct<Product> { created: string; } 

をそれらを表現するインタフェース。 –

答えて

1

私のようなものだろう:

function isClientBoughtProduct(obj: BoughtProduct<any>): obj is ClientBoughtProduct { 
    return typeof obj.product === "number"; 
} 

function isServerBoughtProduct(obj: BoughtProduct<any>): obj is ServerBoughtProduct { 
    return typeof obj.product === "object"; 
} 

if (isServerBoughtProduct(obj)) { 
    // obj.created is available 
} 
1

以前、例えば、それをチェックするタイプの場合は活字体はあなたのためにそれ自動キャストに十分にスマートであるで見ることができます

if (typeof boughtProduct.product === "number" { 
    // it will be handled as number 
} else { 
    // it will be handled as Product 
} 
関連する問題