是否在编译时强制指定了两个道具之一?

时间:2018-10-19 11:55:23

标签: typescript

我有一个样式为Button的组件。

interface Button {
    href?: string;
    action(): void;
}

我希望此Button的使用者传递(XOR)hrefaction作为道具,而不是两者。

我希望TypeScript在编译时强制执行此操作。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用联合类型来指定该类型可以具有一个道具或另一个道具

type Button = {
    href: string;
    action?: never
} | {
    action: () => void;
    href?: never;
}

let b1: Button = { href: "" };
let b2: Button = { action: () => { } };
let b3: Button = { action: () => { }, href: "" }; // error

您需要添加可选的never道具以确保得到错误,这是由于多余的属性检查可以使您阅读更多here的方式所致。您也可以在该答案中使用StrictUnion类型,但仅使用两个属性可能就显得过分了。

相关问题