3

I've got the following TypeScript snippet:

const anchorRef = React.useRef(null);
...
const handleClose = (event: any): void => {
        if (anchorRef != null && anchorRef.current != null && anchorRef.current.contains(event.target)) {
            return;
        }
        setOwnState({ ...ownState, open: false });
    }

...
<Popper placement='top' id='id-popper' open={ownState.open} anchorEl={anchorRef.current} transition disablePortal>
...

Visual Studio is telling me that Object is possibly null @

anchorRef.current.contains

enter image description here

Since I'm doing all the necessary null checking prior to hitting that, how is that even possible?

Edit 1: Currently anchorRef.current only ever is null, but at the point where it is giving me an error, it has been checked for null. I don't really care that, right now, it only ever is null. I just want to get rid of the TS error.

DontThinkJustGo
  • 380
  • 2
  • 11
  • What if you change the first condition to `!== null`? –  Nov 25 '19 at 16:23
  • 2
    Please consider editing the code to constitute a [mcve] as described in the guidelines for [ask]. – jcalz Nov 25 '19 at 16:24
  • might be better to use `if(anchorRef && anchorRef.current ......` – Ric Nov 25 '19 at 16:24
  • no change if using !==. Also no change with if(anchorRef && anchorRef.current... – DontThinkJustGo Nov 25 '19 at 18:07
  • If I actually initialize it to be something other than null, the error goes away. However, my question isn't really about the actual value of the object, but rather, why the null checking isn't being observed by visual studio. – DontThinkJustGo Nov 25 '19 at 18:08

0 Answers0