TS2531:对象可能 'null'

TS2531: Object possibly 'null'

我的打字稿文件 (React-TypeScript) 中有以下代码片段。但是,虽然 运行 我的应用程序出现错误“对象可能为空”,即使在进行空检查后也是如此

if 条件的最后一部分抛出错误

anchorRef.current.contains(...)

  const anchorRef = React.useRef(null);
  const handleClose = (event: React.MouseEvent<Document, MouseEvent> | React.SyntheticEvent) => {
    if (anchorRef !== null && anchorRef.current !== null && anchorRef.current.contains(event.target)) {
      return;
    }

    setOpen(false);
  };

我最近学习了 TypeScript,所以如果有人能在这里突出显示缺失的部分,那就太好了。

谢谢,
苏迪尔

您将初始值设置为null

const anchorRef = React.useRef(null);

useRef hook 的 Typescript 定义声明如下

interface MutableRefObject<T> {
   current: T;
}
function useRef<T>(initialValue: T): MutableRefObject<T>;

interface RefObject<T> {
   readonly current: T | null;
}
function useRef<T>(initialValue: T|null): RefObject<T>;

我相信 Typescript 编译器将 anchorRef.current 的类型推断为 null,因此出现了抱怨。

解决方法是显式设置 current 字段的类型,例如


const anchorRef = React.useRef<SomeType>(null);
// 'any' also works
const anchorRef = React.useRef<any>(null);

您好,我尝试重新创建您的案例,并找到了解决此问题的方法。似乎调试器将 useRef 的初始化作为 null 并且这就是抱怨的原因。我在打字稿中使用关键字 as 来对值进行排序 casting 一旦我确定我已经检查过我将投射的值不为空。

export default function App() {
  const [open, setOpen] = useState<boolean>(false)
  
  const anchorRef = useRef<HTMLButtonElement>(null);
  const handleClose = (event: React.MouseEvent<Document, MouseEvent> | React.SyntheticEvent) => {
    /* if (anchorRef !== null && anchorRef.current !== null && anchorRef.current.contains(event.target)) {
      return;
    } */
    if(!anchorRef){
      return;
    }
    // yout other logic here....
    const coordinates = (anchorRef.current as HTMLButtonElement).getBoundingClientRect();
    console.log(coordinates)
    setOpen(false);
  }; 


  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button ref={anchorRef}>Click me</button>
      <div>
        I am some menu
      </div>
    </div>
  );
}

你可以在使用后看到,因为调试器不再报错了。

在这里,我为您提供了 2 张包含两个示例的图片。使用 as 和不使用它。