【问题标题】:TypeScript strictNullChecks - Object is possibly 'null'TypeScript strictNullChecks - 对象可能是“空”
【发布时间】:2017-05-05 09:10:20
【问题描述】:

在使用 Angular 4.1.1 启用 strictNullChecks 后,null 检查出现多个错误。我已经修复了它们的捆绑包,但无法为 this.form.get('username').value 修复相同的 Object is possibly 'null'。与其他人一样,我也尝试过相同的方法,但无法修复错误。

if (this.form.get('username') != null) {
    body.append('username', this.form.get('username').value);
}

【问题讨论】:

    标签: angular typescript2.0


    【解决方案1】:

    尝试使用Non-null assertion operator 喜欢

    this.form.get('username')!.value; // notice !
    

    【讨论】:

    【解决方案2】:

    你真的不需要在这里投射。实际上,您永远不必这样做。

    最简洁的方式:

    const username = this.form.get('username');
    if (username) body.append('username', username.value);
    

    或退出早期风格:

    const username = this.form.get('username');
    if (!username) return;
    # back to normal flow
    body.append('username', username.value); // no complaint, username cannot be falsy, then it must be { value: string }
    

    编译器无法推断this.form.get('username')null 检查和您在其上使用.value 的时间之间没有变化。

    使用const 变量,它可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2017-09-29
      • 2021-12-01
      • 1970-01-01
      • 2019-11-16
      相关资源
      最近更新 更多