reactjs - 用于道具的 TypeScript 条件类型
问题描述
我有一个组件可以处于两种不同的状态,编辑模式和查看模式。为了适应这一点,我有一个联合类型来完成这项工作,但我仍然让 TypeScript 在我的组件的 args 中抱怨:
type View = {
isEditing: false;
viewHandler: () => void;
someOtherProp: any // this is unique to view mode
};
type Edit = {
isEditing: true;
editHandler: (id: string) => void;
};
export type MyProps = View | Edit;
然后在这里抱怨:
const Item: React.FC<MyProps> = ({
isEditing = false,
editHandler,
~~~~~~~~~~~
}) => {
Property 'editHandler' does not exist on type 'PropsWithChildren<MyProps>'.
我错过了什么?
解决方案
所以我现在使用的解决方案是添加它并将其输入为never
:
type View = {
isEditing: false;
viewHandler: () => void;
editHandler?: never;
};
type Edit = {
isEditing: true;
editHandler: (id: string) => void;
viewHandler?: never;
};
export type MyProps = View | Edit;
在事件处理程序被调用或传递的地方,我使用 a!
来向 TypeScript 保证这不能是未定义的。感谢 Nadia 在上面的评论中为我指明了正确的方向!
推荐阅读
- sql-server - 如何在 Azure SQL 中检查 UNIQUEIDENTIFIER 值的默认值?
- python-3.6 - 为什么我不能在这段代码中打印 x 的值?
- python - Python - 无法导入 sklearn,但适用于其他包
- bash - Shell 脚本:等待组中的任何进程完成
- python - QtDesigner 布局不拉伸(预览不同于 GUI)
- django - 在管理员中显示 django 模型属性
- sql - 如果列中存在某些值,则防止 SQL 用空值覆盖
- arrays - 为什么这会导致分段错误?
- javascript - 将 csv 文件转换为 javascript 对象
- c++ - 寻求帮助将 SOLID 原则应用于文件 I/O 问题