Take this code snippet example:
const [interval, setInterval] = useState<PartialInterval | null>(null);
const handleDaySelect = (day: DateData) => {
const isStartSelected = interval?.start;
const isEndSelected = interval?.end;
if (!isStartSelected) {
setInterval({ start: parseDayToDate(day.dateString) });
return;
}
if (isStartSelected && !isEndSelected) {
const isSelectedEndBeforeSelectedStart = isBefore(
parseDayToDate(day.dateString),
interval.start!,
);
if (isSelectedEndBeforeSelectedStart) {
setInterval({
start: parseDayToDate(day.dateString),
end: interval.start,
});
return;
}
setInterval({ ...interval, end: parseDayToDate(day.dateString) });
return;
}
if (isStartSelected && isEndSelected) {
setInterval({ start: parseDayToDate(day.dateString) });
}
};
Where the null checks for the interval are assigned as a const value at the beginning of the function. In this case, I want to use no-non-null-assertion so I don't have to write each declaration like so interval.start! is this actually achievable in typescript without explicitly doing the check at each if statement? if(interval?.start) and can continue to use the already defined check of isStartSelected.
Thanks in advance!
A handy way will be to use assertive functions to assert and handle the interval is not nullish and upon successful assertion it returns the interval object.
Typescript will never complain about its being null because it is returned from the function.
So the answer here:
Use the assigned const variable you've given at the top of the scope.
So instead of writing the variable isStartSelected and using it as a bool check for undefined, you can assign the variable a better name startInterval and then ts will let you use the variable you've assigned as an undefined check as well as able to parse and use it later in the function.
Simple case of overcomplicating the problem