Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: Is there a cleaner way to null check a hierarchical object structure?

I’m currently null checking an object structure like so:

if (error.response && error.response.data && error.response.data.errorMessage)
{
  // Do stuff
}

All I really want to do is null check the deepest variable error.response.data.errorMessage, but because I want to avoid null pointer exceptions in the check I have to first check error.response, and then error.response.data.

Is there a cleaner way to do this? I imagine as you want to query deeper and deeper into the hierarchy it can get quite messy.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

>Solution :

You can use optional chaining:

if (error.response?.data?.errorMessage) {
  // Do stuff
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading