Search code examples
reactjstslint

TS2531 with useRef


I'm getting an issue TSLink throwing TS2531 (Object is possibly 'null'.) in a code on my project to the point I'm doing the most simple test to isolate the issue.

The point is that I testing the exact same code in a React + TS sandbox on codesandbox and it's working fine. Here is the code:

import React from "react";

export const SimpleComp = () => {
    const refName = React.useRef(null);

    const getValue = (): void => {
        if (refName.current !== null) {
            console.log(refName.current.value);
        }
    };

    return (
        <>
            <input type="text" ref={refName} />
            <button onClick={() => getValue()}>Get Value</button>
        </>
    );
};

My guess it that I can fix it on tsconfig.json, but I'm not sure of how, since I copied the same tsconfig.json from the codesandbox and I'm still having the same issue. BTW, I'm using webstorm.

Any idea of how to fix it?

PS: here is the link for my the codesandbox: https://codesandbox.io/s/competent-franklin-ww4xk


Solution

  • TypeScript can not infer what the reference will be for. You can pass in the HTMLInputElement for the useRef<T> generic function.

    Change:

    const refName = React.useRef(null);
    

    To:

    const refName = React.useRef<HTMLInputElement>(null);