我有一个类型:

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


当前回答

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

"compilerOptions": {

   // other rules

   "strictNullChecks": false
}

其他回答

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

代码没有显示错误。

更新:对象链接是一种访问可能为空或未定义引用的属性的方法

object?.objectProperty?.nextProperty

以前

if (object !== undefined) {
    // continue - error suppressed when used in this way.
}

以前

const objectX = object as string

不过,在选择上述解决方案之前,请考虑您的目标体系结构及其对大局的影响。

在typescript中,您可以执行以下操作来抑制错误:

let subString?: string;

subString > !—注意在null前增加了感叹号。

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

"compilerOptions": {

   // other rules

   "strictNullChecks": false
}

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