javascript - 使用两个 Omit<...> | 键入的 React 组件道具 省略<....> 抛出 TS 错误 2339。Pick |上不存在属性 x 挑选
问题描述
问题的例子。我有一个采用以下道具的组件:
interface OwnProps {
text: string;
tKey: string;
color: string;
height: number;
}
我希望组件接受这些道具,但强制您只能传入 text 道具或 tKey 道具,但不能同时传入两者。所以我是这样写的:
interface Props {
text: string;
tKey: string;
color: string;
height: number;
}
type OwnProps = Omit<Props, 'text'> | Omit<Props, 'tKey'>;
const Component = ({text, tKey, color, height}: Props) {
....
}
OwnProps 类型似乎是正确的。但是,当我解构道具打字稿时,在组件内会引发 ts-2339 错误。当我使用以下接口进行类似设置时:
interface BaseProps {
color: string;
height: number;
}
interface PropsText extends BaseProps {
text: string;
tKey?: never;
}
interface PropsTKey extends BaseProps {
tKey: string;
text?: never;
}
打字稿很好。我想知道是否有关于省略的东西,或者打字稿不满意的类型。理想情况下,找到一个可以使用 Omit 的解决方案会很棒。
在此先感谢您的帮助。
解决方案
您提供的示例不等效:
- Omit 完全删除该属性,因此省略不同属性的类型具有不同的属性集。
- 您的接口都具有相同的属性集。
要合并独占选项,请修改您的 OwnProps:
type OwnProps = (Omit<Props, 'text'> & {text?: never}) | (Omit<Props, 'tKey'> & {tKey?: never});
const Component = ({text, tKey, color, height}: OwnProps) => {
// return ...
}
推荐阅读
- wpf - 是否可以自定义 AvalonEdit 搜索面板按钮图标?
- javascript - Mongoose / MongoDB - 在另一个文档中按数组查询
- android - 如何在对象列表上建模导航抽屉菜单?
- windows - 将 powershell 命令的输出分配给变量
- oracle - 将从 2 个表中选择的 Oracle 查询加入列 a 或 b
- c - 使用socket api,如何将额外的数据结构传递给内核模块中的fd?
- javascript - Firebase PWA 不会在移动浏览器中对离线用户进行身份验证(在桌面上运行良好)
- javascript - Mongodb聚合unionWith操作(如何整合合并?)
- java - ProgressBar 动画卡在屏幕旋转上
- python - 列中值范围的排列序数