我有一个类型:

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


当前回答

在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。

其他回答

尝试像这样调用object:

(<any>Object).dosomething

出现此错误是因为您使用?将它们声明为可选。Typescript会做严格的检查,它不允许做任何未定义的事情。因此,您可以在这里使用(<any> youobject)。

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

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

作为一个选项,您可以使用类型强制转换。如果你从typescript中得到这个错误,这意味着某些变量有类型或未定义:

let a: string[] | undefined;

let b: number = a.length; // [ts] Object is possibly 'undefined'
let c: number = (a as string[]).length; // ok

确保代码中确实存在a。

这个特性被称为“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的另一种选择的答案!

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

"compilerOptions": {

   // other rules

   "strictNullChecks": false
}