0

Sometimes, I want to pass a second argument to a function, but sometimes I don't pass the second argument.

Below is my method:

const updateStartEnd = (newEndDate: any, newStartDate: any) => {
    if (prevDate && newStartDate && newStartDate.isBefore(prevDate, 'd')) {
        setEndDate(newStartDate);
    } else {
        setEndDate(newEndDate);
    }
};

I call this function like below:

const some_function = (newDates: {startDate, endDate}) => {
    if (endDate !== null) {
        updateStartEnd(endDate, startDate);
    } else {
        updateStartEnd(endDate, startDate); //here i dont want to pass startDate as it will not need to check for if condition in the updateStartEnd.
    }
}

Could someone help me with this?

Lauren Yim
  • 12,700
  • 2
  • 32
  • 59
saritha
  • 619
  • 2
  • 12
  • 25
  • Does this answer your question? [How to pass optional parameters while omitting some other optional parameters?](https://stackoverflow.com/questions/30734509/how-to-pass-optional-parameters-while-omitting-some-other-optional-parameters) – Karan Sep 04 '20 at 04:32

2 Answers2

1

Make the parameters optional in updateStartEnd. Then you need to handle inside updateStartEnd when both of these parameters are undefined

const updateStartEnd = (newEndDate?: any, newStartDate?: any) => {
    // rest of the code
};
brk
  • 48,835
  • 10
  • 56
  • 78
0

Since you are using typescript, you can set default parameters. Also, in this approach as you will always get a moment object, && newStartDate becomes a redundant check and can be removed

const updateStartEnd = (newEndDate: moment = moment(), newStartDate: moment = moment()) => {
  if (prevDate && newStartDate.isBefore(prevDate, 'd')) {
    setEndDate(newStartDate);
  } else {
    setEndDate(newEndDate);
  }
};

You can even make the args as optional parameter but then you will have to add logic to validate for undefined

const updateStartEnd = (newEndDate?: moment, newStartDate?: moment) => {
  if (prevDate && newStartDate && newStartDate.isBefore(prevDate, 'd')) {
    setEndDate(newStartDate);
  } else if(!!newEndDate) {
    setEndDate(newEndDate);
  }
};

Also, since you are dealing with dates and you are expecting it to be of type moment, its better to use moment as type instead of any. That way if I call the fuinction:

updateStartEnd(true, true)

it would validate and throw error in advance.

Rajesh
  • 24,354
  • 5
  • 48
  • 79