anderlaini
anderlaini

Reputation: 1831

Cleaner way to check if sub-properties exist

I'm basically trying to check if lote.projeto.id_projeto == 123

So when the sub-properties are not defined it produces cannot read property errors.

Checking each sub-property with this poor code seems to be the only way to avoid those errors.

if(lote['projeto']){
  if(lote['projeto']['id_projeto']){
    if(lote['projeto']['id_projeto'] == 123){
      // ...
    }
  }
}

Is there any easier/cleaner way to do that?

Upvotes: 0

Views: 83

Answers (3)

Tarun1704
Tarun1704

Reputation: 191

Typescript 3.7 comes with the concept of Optional Chaining Read more from the official documentation

so, probably you can do this

lote?.projeto?.id_projeto == 123

If any sub attribute is missing, then the condition will be false.

If you are running on a older version of typescript you have no other way to add && conditions like below

(lote.projeto && lote.projeto.id_projeto && lote.projeto.id_projeto == 123)

Upvotes: 1

StepUp
StepUp

Reputation: 38209

Try to use && operator:

if (lote['projeto']      
   && lote['projeto']['id_projeto'] == 123) {
   // ...        
}

As mdn says about &&:

Syntax: expr1 && expr2
If expr1 can be converted to true, returns expr2; else, returns expr1.

Upvotes: 4

crashmstr
crashmstr

Reputation: 28583

  1. you don't need to test for the property being truthy before testing equality
  2. you can use the new Optional Chaining in Typescript 3.7 if you goal is to test for a value (vs. test for property existing so you can do something in an else)
if (lote.projeto?.id_projeto == 123) {
}

If your property names are determined at run-time, you can use the "optional element access" syntax

if (lote?.['projeto']?.['id_projeto'] == 123) {
}

Upvotes: 1

Related Questions