reactjs - 如何使用反应正确编写条件类型?
问题描述
因此,我正在尝试编写一种道具类型格式,其中如果选择了一个道具,则将丢弃另一个道具。
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}
}
}
但它说
类型“ButtonProps”上不存在属性“to”。类型 '{ onClick: () => void; 上不存在属性 'to' }'.ts(2339`
如何用左右的方式格式化形状时,当一个选择两个都将被丢弃。没有可选项,选择的道具是必需的。
解决方案
我们需要使用类型保护来根据条件适当地缩小类型。为此,我们需要稍微拆分类型,以便在类型保护 + 可读性中进行断言。下面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
}
}
推荐阅读
- c# - 为什么在轮询期间添加一个微小的延迟会降低 CPU 使用率?
- node.js - nodejs 测试在 CircleCI 上随机失败
- php - 无法使用 Codeigniter 从数据库中获取部分数据
- jquery - 在文件上传控件中获取完整路径 - web
- sql - Sql - 从带有条件的查询结果中分配多个变量
- java - 如何将程序参数传递给 java 打包程序?
- javascript - Jquery appendTo 在调整大小时不会这样做
- javascript - 使用VBScript从html中的特定节点提取值
- cordova - Apache cordova app nost 非天蓝色网站可以吗
- r - 如何在 R mallet 中提取具有权重的主题模型结果