why I recieve this error although I make a condition check if the object exists.
Object is possible null or undefined
Code:
{
const inHolidays = useCallback(() => data?.user.holiday_times ? checkIfEmployeeIsInHolidays(data?.user.holiday_times) : null, [data]);
....
inHolidays()
?
<p>Mitarbeiter ist im Urlaub bis zum {format(new Date(inHolidays().end_time), 'PP', { locale: de })}</p>
:
<p>NOT</p>
}
the error comes here in inHolidays().end_time
{format(new Date(inHolidays().end_time)
Why I get this error ? I make a condition check inHolidays() ? : … but not working
2
Answers
Typescript can’t statically determine that the function will return the same value in both calls, so the initial null check does not narrow the return type for the subsequent call. You can work around this by assigning the result to a const:
You have two things that can possibly be null/undefined here: the function itself, and the result of that function call.
I would do the following to avoid calling the function when the function can be null, and to avoid trying to access a property on a null/undefined result.