如何抑制“错误 TS2533:对象可能为‘空’或‘未定义’"? [英] How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

查看:41
本文介绍了如何抑制“错误 TS2533:对象可能为‘空’或‘未定义’"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型:

type tSelectProtected = {
  handleSelector?: string,
  data?: tSelectDataItem[],

  wrapperEle?: HTMLElement,
  inputEle?: HTMLElement,
  listEle?: HTMLElement,
  resultEle?: HTMLElement,

  maxVisibleListItems?: number
}

我声明了一个全局模块变量:

I declare a global module-wise variable:

var $protected : tSelectProtected = {};

我在 function1() 范围内分配适当的值:

I'm assigning proper value in function1() scope:

$protected.listEle = document.createElement('DIV');

稍后在 function2() 范围内,我调用:

Later in function2() scope, I'm calling:

$protected.listEle.classList.add('visible');

我收到 TypeScript 错误:

I'm getting TypeScript error:

error TS2533: Object is possibly 'null' or 'undefined'

我知道我可以使用 if ($protected.listEle) {$protected.listEle} 进行显式检查,以使编译器平静下来,但这对于大多数非平凡情况似乎非常不方便.

I know that I can do explicit check using if ($protected.listEle) {$protected.listEle} to calm down compiler but this seems to be very unhandy for most non trivial cases.

在不禁用 TS 编译器检查的情况下如何或应该如何处理这种情况?

How this situation can or should be handled without disabling TS compiler checks?

推荐答案

此功能称为严格空检查",将其关闭以确保未设置 --strictNullChecks 编译器标志.

This feature is called "strict null checks", to turn it off ensure that the --strictNullChecks compiler flag is not set.

然而,null 的存在已经被描述正如十亿美元的错误,所以看到诸如 TypeScript 之类的语言引入修复程序令人兴奋.我强烈建议保持开启状态.

However, the existence of null has been described as The Billion Dollar Mistake, so it is exciting to see languages such as TypeScript introducing a fix. I'd strongly recommend keeping it turned on.

解决此问题的一种方法是确保值永远不会nullundefined,例如通过预先初始化它们:

One way to fix this is to ensure that the values are never null or undefined, for example by initialising them up front:

interface SelectProtected {
    readonly wrapperElement: HTMLDivElement;
    readonly inputElement: HTMLInputElement;
}

const selectProtected: SelectProtected = {
    wrapperElement: document.createElement("div"),
    inputElement: document.createElement("input")
};

请参阅 Ryan Cavanaugh 的回答,了解另一种选择!

See Ryan Cavanaugh's answer for an alternative option, though!

这篇关于如何抑制“错误 TS2533:对象可能为‘空’或‘未定义’"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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