I'm working on an Angular2 app and I often encounter the following problem: I have an object of some type that could possibly be undefined
, and I need to assign properties of that object to multiple variables or another object properties, so I usually use optional chaining operator to check whether object exists like that:
observable$.subscribe((object: SomeInterface | undefined) => {
this.var1 = object?.prop1;
this.var2 = object?.prop2;
this.var3 = object?.prop3;
});
But I always feel that I'm doing a lot of unnecessary checks, and I think that maybe I should use if statement in this case like so:
observable$.subscribe((object: SomeInterface | undefined) => {
if (object) {
this.var1 = object.prop1;
this.var2 = object.prop2;
this.var3 = object.prop3;
}
});
But in this case I'm feeling like it can be harder to read code? So I guess my question is what is more efficient (I think second option?) and what's better to use from code readability standpoint?