我有一个类型:

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

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

  maxVisibleListItems?: number
}

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

var $protected : tSelectProtected = {};

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

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

稍后在function2()作用域中,我调用:

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

我得到TypeScript错误:

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

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

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


当前回答

当我在tsconfig中将“strict:true”更改为“strict:false”时。Json文件比代码没有显示错误。 添加添加!使用添加的obj like进行签名 模板! .getAttriute(“src”);

代码没有显示错误。

其他回答

这不是OP的问题,但当我意外地将一个参数声明为空类型时,我得到了相同的对象可能是“null”消息:

something: null;

而不是给它赋值为null:

something: string = null;

这是相当啰嗦的,我不喜欢它,但它是唯一对我有用的东西:

if (inputFile && inputFile.current) {
        ((inputFile.current as never) as HTMLInputElement).click()
}

only

if (inputFile && inputFile.current) {
        inputFile.current.click() // also with ! or ? didn't work
}

对我没用。Typesript版本:3.9.7,带有eslint和推荐规则。

从TypeScript 3.7 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html)开始,你现在可以使用?。当访问null或未定义对象上的属性(或调用方法)时获得未定义的操作符:

inputEl?.current?.focus(); // skips the call when inputEl or inputEl.current is null or undefined

很惊讶没有人回答这个问题,你所要做的就是在访问它之前检查对象是否存在,这很直接。否则,请确保在访问对象之前初始化了您的值。

if($protected.listEle.classList) {
   $protected.listEle.classList.add('visible');
}

这不是OP的答案,但我看到很多人在评论中对如何避免这个错误感到困惑。这是通过编译器检查的一种简单方法

if (typeof(object) !== 'undefined') {
    // your code
}

注意: 这行不通

if (object !== undefined) {
        // your code
    }