反应功能组件中的打字稿道具区分

时间:2021-01-15 00:03:17

标签: javascript reactjs typescript typeerror

我正在创建一个动态小部件,它可以是空的,也可以是填充的。默认情况下它应该是空的。当 populated={true} 时,我希望 totalGrosstotalNet 值是必需的。否则,不应允许使用这 2 个道具。

为此,我尝试使用区分类型 (WidgetBodyProps)。但是,TypeScript 会抱怨,因为 totalNettotalGross<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>
    );
};

我该如何修复这个打字稿错误? TS Error

0 个答案:

没有答案