所以我正在尝试编写一种道具类型格式,如果选择了一个道具类型格式,则其他道具将被丢弃。
type ButtonProps = {
to: string,
} | {
onClick: (() => void)
};
export const BackButton = (props: ButtonProps) => {
if(props.to != null) {
//props {to} will be used hence no need for onClick
}
else {
// {onClick} will be used over {to}
}
}
但是它说
“按钮属性”类型上不存在属性“至”。 类型'{onClick:()=> void;类型不存在属性'to'; }'。ts(2339`
如何使用OR格式化类型的形状,因此当选择其中一个时,另一个将被丢弃。没有可选项,则需要选择的道具。
答案 0 :(得分:2)
我们需要使用类型保护来根据条件适当地缩小类型。为了做到这一点,我们需要一点点拆分类型,以便断言类型保护+可读性。在ButtonProps
下面与您的实现相同,但是具有显式指定的并集元素。
第二件事是类型防护,在isButtonWithTo
下面的代码片段中正是这样。它将类型缩小为联合中的选项之一。注意is
关键字,它表明函数表示结果为true的意思,在这种情况下,我说的是如果isButtonWithTo
返回true,则参数的类型为ButtonWithTo
>
type ButtonWithTo = {
to: string,
}
type ButtonWithClick = {
onClick: (() => void)
}
// the same type as orginal but with explicit declarations of union elements
type ButtonProps = ButtonWithTo | ButtonWithClick
const isButtonWithTo = (b: ButtonProps): b is ButtonWithTo => 'to' in b // type guard
export const BackButton = (props: ButtonProps) => {
if(isButtonWithTo(props)) {
props // props have type ButtonWithTo
} else {
props // props have type ButtonWithClick
}
}