Angular 对象是否可能未定义?

Angular 对象是否可能未定义?,angular,typescript,undefined,angular11,Angular,Typescript,Undefined,Angular11,我不明白为什么在这个.selectedBugReport上出现“对象可能是未定义的错误”。我确保它不能是未定义的,并将结果存储在常量中。但这对我来说是个问题吗 错误 const test = this.selectedBugReport !== undefined; if (test) // if (test === true) also errors { // @ts-ignore const i = this.selectedBugReport.id; // << no

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

错误

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
}

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

{
“编译器选项”:{
“检查”:错误,
// .... 
}
}

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

如果
不应该是
如果(This.selectedBugReport)
?这是一个类型脚本问题,而不是角度特定的。您必须更正此键入。selectedBugReport。你用这个做了什么!==undefined将通过推理使其成为布尔值,因此不起作用。因此,如果我在更“复杂”的情况下有这样的情况,比如嵌套的三元运算符,那么我必须在每一行上执行if检查,比如5x?我不能为它定义一个常数?这似乎既低效又难以维持。。。表单组示例:selectProject:[this.isEdit?this.selectedBugReport===undefined?projectId:-1:]这是一行,如果选中每一行,它将包含5个字符。。。会有很多如果支票。。。我100%确信它不能不定义
常量测试:MyDto=this.selectedBugReport(取决于
selectedBugReport
的键入方式)。只有一侧需要显式键入。这不是一个黑客;很清楚你的对象是什么类型的。如果你输入了正确的对象和属性,你不需要任何
if
s。我认为这是一个黑客行为,但显然,这是一个可行的解决方案。如果你能把这个作为一个答案,那么我可以接受。
const test: MyDto = this.selectedBugReport as MyDto; // This line looks stupid to me.
const foo = test.id; // no error, no if-checks required anymore.