You're immediately trying to access the property message
of the res
variable without checking if res
is defined. I'd propose to change the condition to one of the following
Option 1: double-bang operator !!
+ ternary operator ?:
this.systemMessage = (!!res && !!res.message) ? res.message : undefined;
The message
property will only be accessed if res
is defined.
About double-bang operator from here: "Converts Object
to boolean
. If it was falsey (e.g. 0
, null
, undefined
, etc.), it will be false
, otherwise, true
".
We could also use the ternary operator ?:
to simplify the if-else to a single statement.
Option 2: optional chaining operator ?.
this.systemMessage = res?.message;
Essentially the same as option #1, but using the optional chaining operator ?.
. Again, the message
property will only be accessed if res
is defined.
Importantly, from the docs, "instead of causing an error if a reference is nullish
(null
or undefined
), the expression short-circuits with a return value of undefined
". So you could skip explicitly assigning the undefined
.
Option 3: Nullish coalescing operator ??
this.systemMessage = res.message ?? undefined;
The nullish coalescing operator ??
returns the value of LHS (res.message
) if it's defined or the value of RHS (undefined
in your case) if it's LHS is nullish.