在Typescript中的类型中扩展接口

时间:2019-12-28 15:51:57

标签: typescript

container1
container2

我有上面的类型描述。如果您看到interface IType { name: string; label: string; checked?: boolean; disabled?: boolean; } interface Category { name: string; label: string; description: string; } type Data = Array<{ name: string; label: string; description: string; types: IType[]; }>; 具有与interface Category中相同的三个键。如何在我的type Data中引用interface Category,而不重复上面的操作。请注意,我不需要我的type Data中的其他密钥。

谢谢

2 个答案:

答案 0 :(得分:4)

最小的更改是使用intersection type

type Data = Array<Category & {
// −−−−−−−−−−−−−−−^^^^^^^^^^
    types: IType[];
}>;

Live Example

...但是我建议遵循JB's advice并为该数组的内容创建一个类型。

我也可能完全不使用Data类型,但这是风格问题。如果您对内容使用类型,则只需在当前使用ThatType[]的地方使用Data

答案 1 :(得分:4)

为数组的内容引入命名接口,该接口扩展了Category:

interface IType {
    name: string;
    label: string;
    checked?: boolean;
    disabled?: boolean;
}
interface Category {
    name: string;
    label: string;
    description: string;
}

interface DataItem extends Category {
    types: IType[];
}

type Data = Array<DataItem>;