我试图创造一种可以有打字稿接口需要两个属性中的一个存在
export interface MenuItem {
title: string;
component?: any;
click?: any;
icon: string;
}
- 的接口是否有需要
component
或click
要设置 - 的方法是有一个方式要求两个属性不能设置?
我试图创造一种可以有打字稿接口需要两个属性中的一个存在
export interface MenuItem {
title: string;
component?: any;
click?: any;
icon: string;
}
component
或click
要设置我落得这样做:
export interface MenuItem {
title: string;
icon: string;
}
export interface MenuItemComponent extends MenuItem{
component: any;
}
export interface MenuItemClick extends MenuItem{
click: any;
}
然后我用:
appMenuItems: Array<MenuItemComponent|MenuItemClick>;
但希望有办法把它与一个单一的接口模型。
不能与单个接口,因为类型没有条件逻辑和不能依赖于彼此,但可以通过划分接口:
export interface BaseMenuItem {
title: string;
icon: string;
}
export interface ComponentMenuItem extends BaseMenuItem {
component: any;
}
export interface ClickMenuItem extends BaseMenuItem {
click: any;
}
export type MenuItem = ComponentMenuItem | ClickMenuItem;
而不多个接口的替代方案是
export type MenuItem = {
title: string;
component: any;
icon: string;
} | {
title: string;
click: any;
icon: string;
};
我在How to create a Partial-like that requires a single property to be set
有趣问过类似的问题。我以前从未输出“类型”。所以它只是意味着MenuItem可以是一个或另一个? – Nix
我比我在下面做的更好。帮助我理解“类型”的链接http://stackoverflow.com/a/36783051/256793 – Nix
是的:TS的类型是'AND'和'OR'运算符。如果你正在做这样的事情,那么在声明一些单独的类型之后,OR可以很好地给你一个单一的收集的名字。 – ssube