I know you can make props optional with a ?, like this:
type: 'goal' | 'course',
onSaveCourse?: (title: string, date: Date) => void;
onSaveGoal?: (text: string) => void;
But if the prop is a function(as in the snippet above) typescript complains, once such a function is called, that it won't put up with "possibly undefined".
How could this be resolved?
Motivation of the above snippet: It's an edit modal that should be used in two cases ( 'goal' | 'course') and I don't want to be forced to pass the onSave function I don't need for either case.
If you have an typings as below with optional functions:
interface Props {
type: 'goal' | 'course'
onSaveCourse?: (title: string, date: Date) => void
onSaveGoal?: (text: string) => void
}
You can safely use them as:
props.onSaveCourse?.('abc', someDate)
props.onSaveGoal?.('abc')
As optional chaining is also possible with function calls. Using this will not call the function when it is null
or undefined
and TypeScript will also not complain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With