Last updated: Feb 28, 2024
Reading time·3 min
The error "Cannot invoke an object which is possibly 'undefined'" occurs when
we try to invoke a function property that could be undefined
, e.g. is marked
as optional.
To solve the error, use the optional chaining operator (?.), e.g.
employee.doWork?.()
.
Here is an example of how the error occurs.
type Employee = { doWork?: () => void; }; const employee: Employee = {}; // ⛔️ Error: Cannot invoke an object which is possibly 'undefined'.ts(2722) employee.doWork();
Notice that the doWork
function is marked as an
optional property
by using a question mark.
undefined
.To solve the error, use the optional chaining (?.) operator when invoking the function.
type Employee = { doWork?: () => void; }; const employee: Employee = {}; // ✅ Works now employee.doWork?.();
The optional chaining (?.) operator
short-circuits instead of throwing an error if the reference is undefined
or
null
.
undefined
.If the error persists, check out my Object is possibly 'undefined' error in TypeScript article.
The error often occurs in React.js projects when passing props with functions that are marked as optional.
Here is an example.
type ButtonProps = { onClick?: () => void; }; function Button(props: ButtonProps) { // ⛔️ Error: Cannot invoke an object which is possibly 'undefined'.ts(2722) return <button onClick={() => props.onClick()}>Click me</button>; } function App() { return ( <div className="App"> <Button /> </div> ); } export default App;
The onClick
property in the props
object is marked as optional by using a
question mark, so we can't directly invoke the function.
To solve the error, use the optional chaining (?.) operator when calling the function.
type ButtonProps = { onClick?: () => void; }; function Button(props: ButtonProps) { // ✅ works now return <button onClick={() => props.onClick?.()}>Click me</button>; } function App() { return ( <div className="App"> <Button /> </div> ); } export default App;
We used the ?.
syntax when calling the onClick
function, so if the reference
is equal to undefined
or null
, we will just short-circuit returning
undefined
without causing any errors.
On the other hand, if the function is defined, it will be invoked.
undefined
value because trying to invoke undefined
would cause a runtime error.Therefore you could use any of the other approaches that serve as a
type guard to ensure the property is
not undefined
before calling the function.
type Employee = { doWork?: () => void; }; const employee: Employee = {}; const result = employee.doWork && employee.doWork();
The logical AND (&&) operator returns the value to the right if the value to the left is truthy.
Since undefined
is a falsy value, we wouldn't reach the code to the right of
the logical AND (&&) operator if employee.doWork
is undefined
.
If the error persists, check out my Object is possibly 'undefined' error in TypeScript article.