我正在创建一个动态小部件,它可以是空的,也可以是填充的。默认情况下它应该是空的。当 populated={true}
时,我希望 totalGross
和 totalNet
值是必需的。否则,不应允许使用这 2 个道具。
为此,我尝试使用区分类型 (WidgetBodyProps
)。但是,TypeScript 会抱怨,因为 totalNet
和 totalGross
在 <WidgetBodyPopulated />
type WidgetBodyProps =
| { isEmpty?: false; totalNet: string; totalGross: string }
| { isEmpty: true; totalNet?: never; totalGross?: never };
type WidgetProps = WidgetHeaderProps & WidgetBodyProps;
const Widget = (props: WidgetProps) => {
const { title = "", isEmpty = true, totalNet, totalGross } = props;
return (
<Card>
<Box>
<WidgetHeader title={title} />
<Divider my="4" />
{isEmpty ? (
<WidgetBodyEmpty flex="1" />
) : (
<WidgetBodyPopulated totalNet={totalNet} totalGross={totalGross} />
)}
</Box>
</Card>
);
};