reactjs - 如何使道具功能可选
问题描述
我知道您可以使用 ? 使 props 成为可选,如下所示:
type: 'goal' | 'course',
onSaveCourse?: (title: string, date: Date) => void;
onSaveGoal?: (text: string) => void;
但是如果 prop 是一个函数(如上面的代码片段),打字稿会抱怨,一旦调用了这样的函数,它就不会忍受“可能未定义”。
如何解决?
上述代码段的动机: 这是一个编辑模式,应该在两种情况下使用('goal' | 'course'),我不想被迫传递我不需要的 onSave 函数。
解决方案
您可以制作这样的类型:
type YourProps = {
type: 'goal',
onSaveGoal: (text: string) => void;
} | {
type: 'course',
onSaveCourse: (title: string, date: Date) => void;
};
这会
- 强制
onSaveX
根据类型设置函数, - 删除
possibly undefined
.
推荐阅读
- python - 使用 hashlib 在 python 中加密
- c# - 如何使用 NSubstitute 模拟带有多个附件的 Outlook.MailItem?
- python - 从函数返回 matplotlib 图/图形并稍后保存
- c# - 如何从 ALT + TAB 隐藏和显示表单
- python - 数据框中新创建的列需要根据条件更新来自另一列的值
- java - 如何用 Java 数组解决这个算法问题?
- c++ - 构造函数有什么用?
- mysql - 使用'WHERE id IN(ID列表)'的mysql效率
- nginx - Nginx 位置根和代理
- google-tag-manager - 为什么我的 GTM 变量和相应的 FB 像素购买值显示为空,除非我处于预览和调试模式?