In this article, I will show you how to solve the problem of “Cannot invoke an object which is possibly ‘undefined’. In this article, I will show you how to solve the problem when you get the error “Cannot invoke an object which is possibly ‘undefined’.
The type definitions that produce this error are as follows
export type ButtonProps = {
...
handleOnClick?: () => void;
};
If you define it as above, handleOnClick will be a function or undefined.
(property) handleOnClick?: () => void) | undefined
And if you call it normally as shown below, you will get a typescript error.
props.handleOnClick();
// ↑Cannot invoke an object which is possibly 'undefined'.
Cause of the error
“The error “Cannot invoke an object which is possibly ‘undefined’. error means that you cannot treat handleOnClick as if it were passed, even though it may not have been passed.
It is necessary to make a conditional branch using an if statement or something similar.
We will show you how to solve this error in the next section.
How to resolve error
The solution to the “Cannot invoke an object which is possibly ‘undefined’. error in this article is as follows
Error Resolution Method 1: Conditional Branching
The error says, “You can’t treat handleOnClick as if it was always passed, even though handleOnClick may not have been passed”, so the solution is to simply make a conditional branch.
if (props.handleOnClick) props.handleOnClick();
Error Resolution Method 2: Using Typescript’s Optional Chains
The second solution is to use an optional chain.
Optional chains can be used in Typescript 3.7 or later.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
The code using Typescript’s optional chain is shown below.
props.handleOnClick?.();
The above code is equivalent to the following code. It can be written very simply.
props.handleOnClick === null || props.handleOnClick === undefined ? undefined : props.handleOnClick();
conclusion
“The error “Cannot invoke an object which is possibly ‘undefined’. error means that you can’t treat handleOnClick as if it were passed, even though it may not have been.
In this article, we have introduced two ways to solve this error as follows.
The code is as follows
// Use conditional branching
if (props.handleOnClick) props.handleOnClick();
// Use Typescript's optional chain.
props.handleOnClick?.();
コメント