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

前端 未结 5 1919
谎友^
谎友^ 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:44

    const overlayEl = useRef() as MutableRefObject;
    

    It will cast overlayEl to an initiated MutableRefObject that is the returning value of useRef:

    function useRef(): MutableRefObject;
    

    Yet in this case, the compiler will always think that overlayEl has a value.

提交回复
热议问题