#
Table of Contents
-
Cannot invoke an object which is possibly 'undefined' in TS
-
Solve the error in a React.js project
#
Cannot invoke an object which is possibly 'undefined' in TS
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 = {};
employee.doWork();
Notice that the
doWork
function is marked as an
optional property
by using a question mark.
This means that the property can either be a function or have a value of
undefined
.
#
Use the optional chaining (?.) operator to solve the error
To solve the error, use the optional chaining (?.) operator when invoking the
function.
type Employee = {
doWork?: () => void;
const employee: Employee = {};
employee.doWork?.();
The
optional chaining (?.)
operator
short-circuits instead of throwing an error if the reference is
undefined
or
null
.
You can also use this approach to access deeply nested values in an object that has properties that might be
undefined
.
If the error persists, check out my
Object is possibly 'undefined' error in TypeScript
article.
#
Solve the error in a React.js project
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) {
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.
#
Use the optional chaining (?.) operator to solve the error
To solve the error, use the optional chaining (?.) operator when calling the
function.
type ButtonProps = {
onClick?: () => void;
function Button(props: ButtonProps) {
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.
The source of the error is that TypeScript wants us to make sure that the property doesn't have an
undefined
value because trying to invoke
undefined
would cause a runtime error.
#
Using a type guard to solve the 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 = {};