Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

angular - Object is possible undefined?

I don't understand why I'm getting the 'Object is possibly undefined error' on this.selectedBugReport. I make sure that it can't be undefined and store the result in a constant. But that, is a problem for Angular?

Error

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!!
}

No error

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

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

I'm using Angular 11 and the WebStorm IDE if it matters.

Update:

Is this the best practice hack to make it work (for more complex cases to avoid 100+ if-statements)?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The type assertion like MyDto is good but I recommend add this to tsconfig.json:

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

This is safe for runtime errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...