2017-09-14 4 views
0

제가 이야기하는 백엔드에는 주문을 생성하는 API가 있습니다. 이러한 주문에는 고객이받은 제품이 ID로 지정되고 서버가 보낼 때 완전한 상세 개체 인 제품이 있습니다.원활한 방식으로 타이프 스크립트 (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 
} 

그것은 완벽 할 것입니다.
이것은 중첩 배열이므로 캐스트를 사용하면 복잡 할 수 있습니다. 자동으로 당신을 위해 캐스팅에 앞서 예를 확인 입력하면 문제가의

an 더 간단한 예는 똑똑 this playground link

+0

나에게 소리 인터페이스를 나타냅니다. –

답변

1

나는 같은 것을 할 것 : 그럼 난 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; 
} 

을 : 당신이 여기 두 가지 유형이 있고 아마 다른 두 가지가 있어야처럼

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 
}