Home > Net >  Is there a way to always use Optional-chaining in Angular
Is there a way to always use Optional-chaining in Angular

Time:01-06

I am working with an Angular app where the api response can be missing some expected data.

This can crash the app and an easy fix has been to use Optional-chaining;

foo.bar.baz => foo.bar?.baz

Is there a setting or way to treat all '.' as '?.' and would this be a bad idea for any reason?

CodePudding user response:

As far as i went through the official Angular & Typescript docs, There is no such option. And there shouldn't be.

Its definitely a bad idea. This will result in "Silent" bugs, that will be hard to find as the system grows.

e.g. if you have the following model:

interface ContactInfoDTO {
   email: string;
   phone: string;
}

interface UserDTO {
   name: string;
   contactInfo: ContactInfoDTO;
}

And you assume that every user in the system should have a valid contact info. When you access the email property user?.contactInfo?.email, you could end up with a bug, not knowing that something is actually wrong with your data, since no error was thrown.

Use Optional-chaining carefully, only where you know that some data might not be defined for a reason.

There is a nice article on the matter: https://medium.com/@a.hafez852/is-optional-chaining-really-a-good-addition-to-javascript-e4bbbc31909f

  •  Tags:  
  • Related