Typescript, how to pass “Object is possibly null” error?

前端 未结 5 1869
谎友^
谎友^ 2021-02-05 00:16

I\'ve got the \"Object is possibly null\" error many times and usually I use a safety \"if statement\" in case it returns null.

I\'ve got the following function:

<
5条回答
  •  执笔经年
    2021-02-05 00:56

    If you really know that in executing time you dont have a error here then just put :

     (overlayEl as any).current 
    

    If not, better use:

        if (typeof overlayEl !== 'undefined' &&
          typeof overlayEl.current !== 'undefined' &&
          overlayEl.current === null) {          
          return;
        }
    
        // Or
    
        try {
          // you code here ...
          // This is fine way to check by order -> parent.parent.FinalInstance
          // Also try & catch will handle all bad situation about current error
          overlay &&  overlayEl.current && overlayEl.current.focus();
    
        } catch(e){
           console.log("Real null >> ", e);     
        }
    
      // Suggest if i am wrong in syntax somewhere ,this is fast answer ;)
    

提交回复
热议问题