TS2531:对象可能为“ null”

时间:2020-11-01 09:45:58

标签: reactjs typescript react-typescript

我的打字稿文件(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,所以如果有人可以在这里突出显示缺少的部分,那将是很好的。

Thnx,
Sudhir

2 个答案:

答案 0 :(得分:1)

您将初始值设置为null

const anchorRef = React.useRef(null);

useRef钩子的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);

答案 1 :(得分:1)

嗨,我试图重新创建您的案子,但我找到了解决此问题的方法。调试器似乎将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,不使用它。

using as to cast value

possible null