Napoleon
Napoleon

Reputation: 388

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.

Upvotes: 0

Views: 596

Answers (1)

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

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

This is safe for runtime errors.

Upvotes: 1

Related Questions