首页 > 解决方案 > 如何使道具功能可选

问题描述

我知道您可以使用 ? 使 props 成为可选,如下所示:

type: 'goal' | 'course',
onSaveCourse?: (title: string, date: Date) => void;
onSaveGoal?: (text: string) => void;

但是如果 prop 是一个函数(如上面的代码片段),打字稿会抱怨,一旦调用了这样的函数,它就不会忍受“可能未定义”。

如何解决?

上述代码段的动机: 这是一个编辑模式,应该在两种情况下使用('goal' | 'course'),我不想被迫传递我不需要的 onSave 函数。

标签: reactjstypescript

解决方案


您可以制作这样的类型:

type YourProps = {
    type: 'goal',
    onSaveGoal: (text: string) => void;
} | {
    type: 'course',
    onSaveCourse: (title: string, date: Date) => void;
};

这会

  1. 强制onSaveX根据类型设置函数,
  2. 删除possibly undefined.

推荐阅读