如何使 props 函数成为可选

J0h*_*nes 4 typescript reactjs

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

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

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

怎么解决这个问题呢?

上面代码片段的动机: 这是一个编辑模式,应该在两种情况下使用(“目标”|“课程”),我不想被迫传递两种情况都不需要的 onSave 函数。

Aje*_*hah 10

如果您有如下带有可选功能的打字:

interface Props {
  type: 'goal' | 'course'
  onSaveCourse?: (title: string, date: Date) => void
  onSaveGoal?: (text: string) => void
}
Run Code Online (Sandbox Code Playgroud)

您可以安全地将它们用作:

interface Props {
  type: 'goal' | 'course'
  onSaveCourse?: (title: string, date: Date) => void
  onSaveGoal?: (text: string) => void
}
Run Code Online (Sandbox Code Playgroud)

由于可选链接也可以通过函数调用实现。使用 this 不会在函数为nullor时调用该函数undefined,并且 TypeScript 也不会抱怨。