Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TS2721: Cannot invoke an object which is possibly 'null'

TS2721: Cannot invoke an object which is possibly ‘null’.

latestHandler.current(event) // TS2721: Cannot invoke an object which is possibly ‘null’.

hover to latestHandler.current(event)
// const latestHandler: React.MutableRefObject<((event: MouseEvent) => void) | null>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t understand how to solve the type problem

I use a hook useLatest()

export const useLatest = <T>(value: T) => {
  const ref = useRef<T | null>(null)

  useLayoutEffect(() => {
    ref.current = value
  }, [value])

  return ref
}

Next, I use it in

export const useOnClickOutside = <T extends HTMLElement = HTMLElement>(
  ref: RefObject<T>,
  handler: (event: MouseEvent) => void,
  attached = true
) => {
  const latestHandler = useLatest(handler)

  useEffect(() => {

    if (!attached) return

    const listener = (event: MouseEvent) => {
      if (!ref.current || ref.current.contains(event.target as Node)) {
        return
      }

      latestHandler.current(event)
    }
    document.addEventListener('mousedown', listener)
    return () => {
      document.removeEventListener('mousedown', listener)
    }
  }, [ref, latestHandler, attached])
}

I don’t understand how to solve the type problem TS2721: Cannot invoke an object which is possibly ‘null’.

>Solution :

In the useLatest hook the ref has an initial value of null, which causes latestHandler to have a type of React.MutableRefObject<((event: MouseEvent) => void) | null>. You either have to pass the default value to useLatest instead of assigning null as the value, or you can use optional chaining to call the function:

latestHandler.current?.(event);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading