ts2531 the object is possibly ‘null’

Hi i tried to recreate your case and i found a solution to this problem. It seems that the debugger take the initialization of useRef as null and there is the reason why is complaining. I make use of the keyword as in typescript to make sort of casting of the value once i am sure i have checked the value i will cast is is not null.

export default function App() {
  const [open, setOpen] = useState<boolean>(false)
  const anchorRef = useRef<HTMLButtonElement>(null);
  const handleClose = (event: React.MouseEvent<Document, MouseEvent> | React.SyntheticEvent) => {
    /* if (anchorRef !== null && anchorRef.current !== null && anchorRef.current.contains(event.target)) {
    } */
    // yout other logic here....
    const coordinates = (anchorRef.current as HTMLButtonElement).getBoundingClientRect();

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button ref={anchorRef}>Click me</button>
        I am some menu

You can see after using as the debugger is not complaining anymore.

Here i let you 2 images with both examples. Using as and without it.

using as to cast value

possible null

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top