我有一个类型:

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


当前回答

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

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和推荐规则。

其他回答

这个解决方案对我很有效:

转到tsconfig。. json并添加"strictNullChecks":false

如果您从外部知道表达式不是空或未定义的,则可以使用非空断言操作符!为了赶走这些类型:

// Error, some.expr may be null or undefined
let x = some.expr.thing;
// OK
let y = some.expr!.thing;

与'object is possibly null'编译错误相关,如果你想在你的typescript配置中禁用这个检查,你应该在tsconfig中添加下面的行。json文件。

"compilerOptions": {

   // other rules

   "strictNullChecks": false
}

我在使用Angular (11.x)时遇到了这个问题。在前一天,我移动了一段HTML/组件到一个单独的-较小的-组件。第二天,我的电脑关机了,我的项目无法构建。 结果是.html组件出了问题。如前所述,这是零安全。

以下(节选):

<div class="code mat-body-strong">{{machine. "productCode}} < / div >

:

<div class="code mat-body-strong">{{machine?。productCode}} < / div >

在angular中,我使用:

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const sum = row
    .filter(p => p.priceInCents !== undefined)
    .reduce((sum, current) => sum + current.priceInCents, 0);

因为只是使用@ts-ignore, eslint会抱怨它禁用了编译错误,这就是为什么我添加了eslint-disable-next-line。