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>
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);