skip to Main Content

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


  1. 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:

    const currentlyInHolidays = inHolidays();
    currentlyInHolidays
        ?
        <p>Mitarbeiter ist im Urlaub bis zum {format(new Date(currentlyInHolidays.end_time), 'PP', { locale: de })}</p>
        :
        <p>NOT</p>
    
    Login or Signup to reply.
  2. 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.

    {
      const inHolidays = useCallback(() => data?.user.holiday_times ? checkIfEmployeeIsInHolidays(data?.user.holiday_times) : null, [data]);
      const inHolidaysResult = inHolidays && inHolidays();
    ....
       inHolidaysResult 
        ?
        <p>Mitarbeiter ist im Urlaub bis zum {format(new Date(inHolidaysResult.end_time), 'PP', { locale: de })}</p>
        :
        <p>NOT</p>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search