TS2722
error TS2722: Cannot invoke an object which is possibly ‘
undefined
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Method invocation only works if the method is defined. The onClick
method of the event
object in the example above is optional, which means it can be undefined
. That’s why we have to make an existence check before calling / invoking it:
1 |
|
As of TypeScript 3.7 you can also use the optional chaining (?.
) operator to call a method on an object if it exists:
1 |
|
A third possibility is to use reference validation:
1 |
|