I'm creating a dynamic Widget, which can be either empty or populated. It should be by default empty. When populated={true}, I'd like the totalGross and totalNet values to be required. Otherwise, those 2 props shouldn't be allowed.
For that, I'm trying to use a discriminating type (WidgetBodyProps). However, TypeScript complains because totalNet & totalGross are required props in <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>
);
};
