0

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.

balteo
  • 23,602
  • 63
  • 219
  • 412
  • If this is happening you aren't using the compiler effectively; it needs to know when a value might be undefined. – jonrsharpe Aug 04 '19 at 08:03
  • @jonrsharpe Thanks for your reply. Can you please kindly elaborate on you comment? Perhaps by providing examples. – balteo Aug 04 '19 at 08:07
  • See e.g. http://www.typescriptlang.org/docs/handbook/interfaces.html#optional-properties, http://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters – jonrsharpe Aug 04 '19 at 08:09
  • There's a nice article (by Nadeesha Cabral) here: https://codeburst.io/how-to-handle-deeply-nested-nullable-fields-in-javascript-and-typescript-5ef3f38c92d9 proposing several solutions amongst which optional chaining upcoming in typescript 3.7. – balteo Sep 25 '19 at 16:41

0 Answers0