对象可能未定义?

时间:2021-01-06 14:51:25

标签: angular typescript undefined angular11

我不明白为什么我会在 this.selectedBugReport 上收到“对象可能未定义的错误”。我确保它不能是未定义的并将结果存储在一个常量中。但这对 Angular 来说是个问题吗?

错误

const test = this.selectedBugReport !== undefined;
if (test) // if (test === true) also errors
{
  // @ts-ignore
  const i = this.selectedBugReport.id; // << no error because of ignore

  const h = this.selectedBugReport.id; // <<< error!!
}

没有错误

if (this.selectedBugReport !== undefined)
{
  // @ts-ignore
  const i = this.selectedBugReport.id; // << no error

  const h = this.selectedBugReport.id; // <<< no error
}

如果重要的话,我正在使用 Angular 11 和 WebStorm IDE。

更新:

这是使其工作的最佳实践黑客吗(对于更复杂的情况,以避免 100 多个 if 语句)?

const test: MyDto = this.selectedBugReport as MyDto; // This line looks stupid to me.
const foo = test.id; // no error, no if-checks required anymore.

1 个答案:

答案 0 :(得分:1)

MyDto 这样的类型断言很好,但我建议将其添加到 tsconfig.json:

{
    "compilerOptions": {
        "strictNullChecks": false,
        // .... 
    }
}

这对于运行时错误是安全的。