Shamoon
Shamoon

Reputation: 43491

With TypeScript, how can I extend an interface that can be one of multiple types?

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

type SkuItemsErrSkuResponse = {
    errorCode: string;
    errorMessage: string;
}

export interface GetSkuItemsResponse extends Array<SkuItem> | SkuItemsErrSkuResponse {}

However, this gives an error:

An interface can only extend an identifier/qualified-name with optional type arguments.ts(2499)

What am I doing wrong? And more importantly, how do I do it right?

Upvotes: 3

Views: 2323

Answers (2)

crashmstr
crashmstr

Reputation: 28563

An interface can extend more than one interface (i.e. combine them completely), but the Array makes it a bit weird and since you want it to be one type or the other, extends will not work.

You can instead do this with type.

type ChildSkuItem = {};

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

type SkuItemsErrSkuResponse = {
    errorCode: string;
    errorMessage: string;
}

export type GetSkuItemsResponse = SkuItem[] | SkuItemsErrSkuResponse;

let x: GetSkuItemsResponse = { errorCode: '', errorMessage: '' };
let xx: GetSkuItemsResponse = [];

Typescript Playground

Upvotes: 2

Emil Laine
Emil Laine

Reputation: 42828

You can't extend, you have to use an intersection type:

export type GetSkuItemsResponse = (Array<SkuItem> | SkuItemsErrSkuResponse) & {
    ...
}

TypeScript Playground

Upvotes: 2

Related Questions