user9847788
user9847788

Reputation: 2431

Is there a ? ("safe operator") alternative in Typescript to deal with null values?

In my Angular app, I'm trying to show/hide a div using ngIf.

Below is my HTML:

<div *ngIf="damageReportToPolice()">
</div>

And here is my typescript:

public damageReportToPolice(): boolean {      
 if(this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].injuryType.value.value === 'Burglary in the car') {
          return true;
        } else {
          return false;
        }
      }

This is working fine when the page loads, & when the condition is true the div is displaying.

But, when I reset() the form, I get the following error:

Cannot read property 'value' of null

When I had this conditional in my HTML, I was able to use ? as a safe operator like so:

damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value?.value === 'Burglary in the car'

But I can't seem to find a typescript alternative to this.

Can someone please tell me if there's a safe operator I can use? Or how I can get around this issue?

Thanks a lot in advance!

Upvotes: 1

Views: 1202

Answers (1)

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10464

Just out of curiosity, that's named elvis operator (Ref. Kotlin) and it's also a javascript proposal that could come out in next ES specifications. There's no a short solution for typescript/javascript, if you don't want to chain it like

injuryType && injuryType.value && injuryType.value.value

then you can just create a function that returns null in case of exception:

export function safeNavigation(cb) {
  try {
    return cb();
  } catch (error) {
    return null;
  }
};




// In the component...
if (safeNavigation(() => injuryType.value.value) === 'Burglary in the car') {
...

PS. If it doesn't casue conflicts, I like to rename it as _ and use it like _(() => path.to.navigate)

Upvotes: 2

Related Questions