TS2532
error TS2532: Object is possibly ‘undefined’.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript warns us that person
can be undefined
(because of the ?
). There are multiple ways to fix the problem. We can do an existence check using an if
-condition:
1 |
|
Alternatively, we can use optional chaining:
1 |
|
Optional chaining is less preferable in this case as it will log undefined
if the person
is undefined
. Using the if
-condition from the solution above, nothing will be logged to the console in case the person
is undefined
.