如何使TypeScript接口成为2种可能的类型之一,其中一种是数组?

时间:2019-09-23 15:48:17

标签: typescript

我正在尝试:

type SkuItem = ChildSkuItem & {
    childSkus: ChildSkuItem[],
};

type GetSkuItemsResponseType = Partial<Array<SkuItem>> & {
    errorCode?: string;
    errorMessage?: string;
}

Partial<GetSkuItemsErrSkuResponse> { }
export interface GetSkuItemsResponse extends GetSkuItemsResponseType { }

因此GetSkuItemsResponse可以是SkuItem的数组,也可以是具有属性errorCodeerrorMessage的对象。

但是,随着我的了解,这似乎不起作用

 Argument of type '{ errorCode: string; errorMessage: string; }' is not assignable to parameter of type 'GetSkuItemsResponse'.
  Type '{ errorCode: string; errorMessage: string; }' is missing the following properties from type 'GetSkuItemsResponse': length, pop, push, concat, and 26 more.

1 个答案:

答案 0 :(得分:1)

@shamoon-如果您使用'or'(|)而不是'and'(&),则您的类型适合您想要的类型。但是,您不能再将其设为接口,因为类可以实现接口,并且不能轻松实现两种可能类型中的一种或另一种。考虑下面的代码-这不是您想要的吗?

interface ChildSkuItem {
    id: number;
    value?: string;
}
type SkuItem = ChildSkuItem & {
    childSkus: ChildSkuItem[],
};
type GetSkuItemsResponseType = Partial<Array<SkuItem>> | {
    errorCode?: string;
    errorMessage?: string;
}
// Can't make GetSkuItemsResponseType into an interface with this definition...
//interface GetSkuItemsResponse extends GetSkuItemsResponseType { }

function test() {
    const sku1: ChildSkuItem = { id: 1, value: "A Value" };
    const sku2: ChildSkuItem = { id: 2 };
    const sku3: ChildSkuItem = { id: 3 };
    const skuItem1: SkuItem = { id: 104, childSkus: [sku1, sku2] };
    const skuItem2: SkuItem = { id: 105, childSkus: [sku3] };
    // GetSkuItemsResponseType can have error info...
    const rt: GetSkuItemsResponseType = { errorCode: "100", errorMessage: "screwed" };
    // ...or it can have an array of skuItems
    const rt2: GetSkuItemsResponseType = [skuItem1, skuItem2];
};