swo*_*opy 2 typescript reactjs react-typescript
所以我正在尝试编写一种道具类型格式,其中如果选择一个道具,则另一个道具将被丢弃。
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}
}
}
Run Code Online (Sandbox Code Playgroud)
但它说
类型“ButtonProps”上不存在属性“to”。类型 '{ onClick: () => void; 上不存在属性 'to' }'.ts(2339`
如何使用 OR 格式化类型形状,以便在选择其中之一时,另一个将被丢弃。没有选项,所选择的道具是必需的。
我们需要使用类型保护来根据条件适当缩小类型。为此,我们需要对类型进行一点分割,以便在类型保护+可读性中进行断言。下面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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1148 次 |
| 最近记录: |