0

I need to show a welcome-modal to user on his first time to that page.

This code works fine:

if(this.app_data) {
  if(this.app_data['company']){
    if(this.app_data['company']['welcomed'] === false){
      this.openWelcomeModal();
    }
  }
}

The problem is the messy code checking nested variable structure.

The clear way to do it would be use a single line like this:

if(this.app_data['company']['welcomed'] === false){
  this.openWelcomeModal();
}

But this generates error:

    core.js:7376 ERROR TypeError: Cannot read properties of undefined (reading 'welcomed')
        at SafeSubscriber._next (game.page.ts:46:39)

Is there any way to do it in a single line, without need to check each level of nested object?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
anderlaini
  • 1,593
  • 2
  • 24
  • 39
  • Does this answer your question? [Test for existence of nested JavaScript object key](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) – Heretic Monkey Jan 03 '23 at 20:20

1 Answers1

5

Optional chaining to the rescue!

if(this.app_data?.['company']?.['welcomed'] === false){
  this.openWelcomeModal();
}
nate-kumar
  • 1,675
  • 2
  • 8
  • 15
  • this generates compile error on dots `error TS1109: Expression expected.`... i'm only able to use this syntax without error on template parsing. – anderlaini Jan 03 '23 at 20:17
  • The syntax above is valid, check this TypeScript playground: https://tsplay.dev/mAd1RN. You may have another syntax issue in your code? – nate-kumar Jan 03 '23 at 20:21
  • 2
    @anderlaini Please [edit] your question to show a [mre] that displays the error you are encountering. – Heretic Monkey Jan 03 '23 at 20:22