我有一个类型:

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编译器检查的情况下如何处理这种情况?


当前回答

从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

其他回答

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

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

注意: 这行不通

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

如果你知道该类型永远不会为null或未定义,你应该声明为foo: Bar,不带?类型声明?条形语法意味着它可能是未定义的,这是您需要检查的。

换句话说,编译器正在做你要求它做的事情。如果您希望它是可选的,您稍后需要检查。

这个特性被称为“strict null checks”,关闭它时要确保没有设置编译器标志——strictNullChecks。

然而,null的存在被描述为“十亿美元的错误”,所以看到像TypeScript这样的语言引入修复是令人兴奋的。我强烈建议你把它开着。

解决这个问题的一种方法是确保值永远不是null或undefined,例如通过预先初始化它们:

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

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

不过,请参阅Ryan Cavanaugh的另一种选择的答案!

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

代码没有显示错误。

从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