Reputation: 1831
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
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
Reputation: 38209
Try to use &&
operator:
if (lote['projeto']
&& lote['projeto']['id_projeto'] == 123) {
// ...
}
Syntax: expr1 && expr2
If expr1 can be converted to true, returns expr2; else, returns expr1.
Upvotes: 4
Reputation: 28583
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