打字稿,如何传递“对象可能为空"错误? [英] Typescript, how to pass "Object is possibly null" error?

查看:32
本文介绍了打字稿,如何传递“对象可能为空"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次收到对象可能为空"错误,通常我会使用安全的if 语句"以防它返回空值.

I've got the "Object is possibly null" error many times and usually I use a safety "if statement" in case it returns null.

我有以下功能:

const ModalOverlay = (props: any[]) => {
  const overlayEl = useRef(null);
    useEffect(() => {
    overlayEl.current.focus();
    });
    return <div {...props} ref={overlayEl} />;
  }

但是 overlayEl.current 得到错误对象未定义".所以我试过了:

But overlayEl.current gets the error "Object is not defined". So I've tried:

if (!overlayEl) {
    return null
  } else {
    useEffect(() => {
    overlayEl.current.focus();
    });
    return <div {...props} ref={overlayEl} />;
  }

这没有用.我也试过:

overlay && overlayEl.current.focus();

任何提示将不胜感激!谢谢

Any hints would be highly appreciated! Thanks

推荐答案

当你声明 const overlayEl = useRef(null);使它出来的类型为 null,因为这是它可以提供的最好的推断与这么多信息,给打字稿更多的信息,它会按预期工作.

When you declare const overlayEl = useRef(null); Makes the type it comes out as is null because that's the best possible inference it can offer with that much information, give typescript more information and it will work as intended.

试试....

 const overlayEl = useRef<HTMLDivElement>(null);

或者一些语法糖,如果你不关心它何时 undefined 是做这样的事情.

Alternatively some syntax sugar for if you don't care for when its undefined is to do something like this.

const overlayEl = useRef(document.createElement("div"))

使用上述语法,所有常见的 DOM 方法只返回默认值,例如0";即overlayEl.offsetWidth、getBoundingClientRect等

using the above syntax all common DOM methods just return defaults such as "0" i.e overlayEl.offsetWidth, getBoundingClientRect etc.

用法:

if(overlayEl.current) {
    // will be type HTMLDivElement NOT HTMLDivElement | null
    const whattype = overlayEl.current; 
}

这种工作方式是打字稿静态分析足够聪明,可以找出if检查guards"反对 null,因此它将从 null | 的联合中删除它作为可能的类型.括号内的 HTMLDivElement.

The way this works is typescripts static analysis is smart enough to figure out that if check "guards" against null, and therefore it will remove that as a possible type from the union of null | HTMLDivElement within those brackets.

这篇关于打字稿,如何传递“对象可能为空"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆