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 array of arrays of arrays: protect from undefined

I am parsing a complex object in Typescript, so have something like:

const a = reply['price']['value']['total']['value'];

and I like to ensure that all elements are defined in the chain, otherwise, it should set a=0 and do not trigger an exception if some of the chained keys are in fact undefined.

What would be the appropriate syntax for that?

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

>Solution :

If you’re using modern JS you can use nullish coalescing and optional chaining

const a = reply?.['price']?.['value']?.['total']?.['value'] ?? 0;

Try to avoid using || instead of ??, because that will give you 0, if the final value is any falsy value, like 0 or false.

If you don’t want to use nullish coalescing, you can do this, which achieves the same.

const a = reply?.['price']?.['value']?.['total']?.['value'] ? reply['price']['value']['total']['value'] : 0;
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