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?
CodePudding user response:
Optional chaining
to the rescue!
if(this.app_data?.['company']?.['welcomed'] === false){
this.openWelcomeModal();
}
CodePudding user response:
Try optional chaining to check each part without nesting everything.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html