Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a props function optional

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.

like image 897
J0hannes Avatar asked Sep 14 '25 16:09

J0hannes


1 Answers

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.

like image 185
Ajeet Shah Avatar answered Sep 17 '25 07:09

Ajeet Shah