我有一个类型:

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

以下(节选):

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

:

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

其他回答

在ReactJS中,我检查构造函数中的变量是否为空,如果为空,我将其视为异常并适当地管理异常。如果变量不为空,代码继续运行,编译器在那之后不再抱怨:

private variable1: any;
private variable2: any;

constructor(props: IProps) {
    super(props);

    // i.e. here I am trying to access an HTML element
    // which might be null if there is a typo in the name
    this.variable1 = document.querySelector('element1');
    this.variable2 = document.querySelector('element2');

    // check if objects are null
    if(!this.variable1 || !this.variable2) {
        // Manage the 'exception', show the user a message, etc.
    } else {
        // Interpreter should not complain from this point on
        // in any part of the file
        this.variable1.disabled = true; // i.e. this line should not show the error
    }

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

object?.objectProperty?.nextProperty

以前

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

以前

const objectX = object as string

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

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

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

注意: 这行不通

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

在设置状态和使用map时,我用React遇到了这个问题。

在这种情况下,我正在做一个API获取调用和响应的值是不知道的,但应该有一个值“答案”。我为此使用了一个自定义类型,但因为该值可能为空,所以我得到了一个TS错误。允许类型为null并不能解决这个问题;或者,您也可以使用默认参数值,但这对我的情况来说很混乱。

我克服了它,通过提供一个默认值,在事件响应是空的,只需使用三元操作符:

this.setState({ record: (response.Answer) ? response.Answer : [{ default: 'default' }] });

注意:这可能不是一个推荐的操作-也许解决方案是实际解决错误。所有的检查都是有原因的,所以禁用它们并不总是正确的做法,但是……

与上面的一些问题的答案相似,但最后有一点不同。我在多次不同的检查中遇到了问题,帮助我的是在tsconfig.json中设置一个严格的属性为false。似乎是上述特定检查的一种更通用的变体。

  "compilerOptions": {
    "strict": false
  },