2017-09-14 62 views
0

我所說的後端有一個API來創建訂單。 這樣的訂單有產品,當客戶端接收到的產品只是由ID指定的,當由服務器發送時,它們是完整的詳細對象。以無縫方式使用打字稿工會

的打字稿接口將是這樣的:

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 
} 

這將是完美的,如果打字稿解釋就當我使用的產品爲數字或接收的產品爲對象,瞭解沒有明確的強制轉換。
這是因爲,因爲它是嵌套數組,所以使用強制轉換將會很複雜。有問題的

一個更簡單的例子可以在this playground link

+0

聽起來像你對我有兩種不同類型的這裏,你或許應該有兩個不同接口來表示它們。 –

回答

1

我會做這樣的事情:

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

然後我會使用user defined type guards

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 
}