对象可能未定义?
Object is possible undefined?
我不明白为什么我在 this.selectedBugReport 上收到 'Object is possibly undefined error'。我确保它不能未定义并将结果存储在常量中。但这对 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.
像 MyDto
这样的类型断言很好,但我建议将其添加到 tsconfig.json:
{
"compilerOptions": {
"strictNullChecks": false,
// ....
}
}
这对于运行时错误是安全的。
我不明白为什么我在 this.selectedBugReport 上收到 'Object is possibly undefined error'。我确保它不能未定义并将结果存储在常量中。但这对 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.
像 MyDto
这样的类型断言很好,但我建议将其添加到 tsconfig.json:
{
"compilerOptions": {
"strictNullChecks": false,
// ....
}
}
这对于运行时错误是安全的。