带有 useRef 的 TS2531

TS2531 with useRef

我在项目代码中遇到 TSLink 抛出 TS2531(对象可能是 'null'。)的问题,我正在做最简单的测试来隔离问题。

关键是我在 codesandbox 上的 React + TS 沙箱中测试了完全相同的代码,它工作正常。这是代码:

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>
        </>
    );
};

我猜我可以在 tsconfig.json 上修复它,但我不确定如何修复,因为我从 codesandbox 复制了相同的 tsconfig.json,但我仍然有相同的问题。顺便说一句,我正在使用 webstorm。

知道如何解决吗?

PS:这是我的代码框的 link:https://codesandbox.io/s/competent-franklin-ww4xk

TypeScript 无法推断引用的用途。您可以为 useRef<T> 泛型函数传入 HTMLInputElement

变化:

const refName = React.useRef(null);

收件人:

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