I work on a large Angular/Typescript project and I very frequently encounter such errors as:
ERROR TypeError: Cannot read property ‘completeness’ of undefined
This happens for example in a create/update form when used in create mode when the object (i.e. a plan
here) is still undefined
.
See:
if (this.plan.completeness === 'COPYING') { //plan is undefined in create mode
...
We then go to fix the problem as follows:
if (this.plan && this.plan.completeness === 'COPYING') {//Ensure plan is truthy regardless of whether it is in create or update mode
...
Note this can also happen with nested objects such as:
const person = {name: 'John', address: {country: 'UK', street: '10 Downing Street'}}
If address
is undefined
and I try dereferencing the street
as follows:
person.address.street;
I will obviously get the same kind of TypeError
...
Our codebase contains a tremendous amount of checks such as:
if (person && person.address & person.address.street) {
// do something with the street
}
I find this lame and noisy.
Quite independently of the above specific cases, I am looking for more elegant patterns or techniques to reduce this kind of dereferencing errors.
Any hint or pointer are welcome.