TS2722

error TS2722: Cannot invoke an object which is possibly ‘undefined‘.

Broken Code ❌

1
2
3
4
5
function handleClick(event: {
onClick?: () => {}
}): void {
event.onClick();
}

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
2
3
4
5
6
7
function handleClick(event: {
onClick?: () => {}
}): void {
if (event.onClick) {
event.onClick();
}
}

As of TypeScript 3.7 you can also use the optional chaining (?.) operator to call a method on an object if it exists:

1
2
3
4
5
function handleClick(event: {
onClick?: () => {}
}): void {
event.onClick?.();
}

A third possibility is to use reference validation:

1
2
3
4
5
function handleClick(event: {
onClick?: () => {}
}): void {
event.onClick && event.onClick();
}