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

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

    Add a type to the ref as mentioned by @Shanon Jackson:

    const linkRef = useRef(null);
    

    And then, make sure you check for null value before using current:

    if (linkRef.current !== null) {
      linkRef.current.focus();
    }
    

    This will satisfy Typescript. Whereas either by itself wouldn't.

    Using any or casting in order to "trick" the compiler defeats the purpose of using Typescript, don't do that.

提交回复
热议问题