TypeScript will not let you call a function that might be undefined
error TS2722: Cannot invoke an object which is possibly 'undefined'.Short answer
TS2722 means the value you are calling has the type 'function | undefined'. That happens with optional props and optional parameters when strictNullChecks is on. Either check the value before the call, use the optional call form fn?.(), or remove the question mark so callers must pass it.
Fix it fast
1Find out which cause you have
Hover the name in the line the error points at. If the type ends in '| undefined', it is declared optional (a '?') and you are calling it unchecked. Then confirm strict mode is on, because that is what makes the compiler report it.
grep -n "strict" tsconfig.json npx tsc --noEmit2Match what you see, then jump to its fix
- 1
onChange?: (value: string) => void in the props type, and onChange(value) in the bodyAn optional callback prop is called without a checkFix - 2
Several optional callbacks, each wrapped in the same if blockYou want a short form that does nothing when the callback is missingFix - 3
Every caller already passes the functionThe value is not really optionalFix
- 1
What does the error look like?
error TS2722: Cannot invoke an object which is possibly 'undefined'.Cannot invoke an object which is possibly 'undefined'.ts(2722)
Cause 1 of 3
An optional callback prop is called without a check
1Check
Look at the props interface. A property with a question mark can be undefined, and with strictNullChecks on, TypeScript reports it when you read it and then call it.
grep -n "?:" src/components/*.tsx2Fix
Test the value first. Inside the if block the type is narrowed to the function, so the call is allowed.
type Props = { onChange?: (value: string) => void };
function Field({ onChange }: Props) {
function handle(v: string) {
if (onChange) {
onChange(v);
}
}
return <input onChange={(e) => handle(e.target.value)} />;
}3Verify
Run the compiler. The error for that line is gone and no other errors appeared.
npx tsc --noEmitConfirmed by typescriptlang.org
Cause 2 of 3
You want a short form that does nothing when the callback is missing
1Check
Decide whether skipping the call is the right behaviour when the caller passed nothing. If yes, the optional call syntax says exactly that.
grep -n "onChange\|onSubmit\|onClose" src/components/*.tsx2Fix
Put ?. before the argument list. The call runs only when the value is not null or undefined.
function Dialog({ onClose }: { onClose?: () => void }) {
return <button onClick={() => onClose?.()}>Close</button>;
}3Verify
The file compiles, and clicking the button with no onClose given does nothing instead of throwing.
npx tsc --noEmitConfirmed by typescriptlang.org
Cause 3 of 3
The value is not really optional
1Check
If the component cannot work without the callback, the question mark in the type is the mistake, and the guard only hides it.
grep -rn "<Dialog" src2Fix
Remove the question mark so TypeScript forces every caller to pass it, and no check is needed inside.
type Props = { onClose: () => void };
function Dialog({ onClose }: Props) {
return <button onClick={onClose}>Close</button>;
}3Verify
Compile again. Any caller that forgot the prop is now reported, which is the point.
npx tsc --noEmitConfirmed by typescriptlang.org
How do I stop it coming back?
- Keep strict on in tsconfig.json so these mistakes show in the editor and not as runtime crashes.
- Mark a prop optional only when the component has a sensible behaviour without it.
- Avoid the non-null assertion (!) to silence this error, because it moves the failure to runtime.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
TypeScript says e.target.files is possibly null in a file input
Object is possibly 'null' on e.target.files[0]
With strictNullChecks on, TypeScript types files on an input as possibly null, so reading files[0] directly is an error.
3 causes, each with a fixWeb apps
TypeScript refuses JSX because the jsx option is not set
TS17004: Cannot use JSX unless the '--jsx' flag is provided.
TypeScript compiles JSX only when you name the file with a .tsx extension and enable the jsx compiler option.
2 causes, each with a fixWeb apps
TypeScript rejects a component that returns an array or other non-Element
Its return type 'Element[]' is not a valid JSX element.
TypeScript before 5.1 required every component to return JSX.Element or null, so arrays, strings and Promises were rejected even though React renders them.
2 causes, each with a fixWeb apps
ESLint says it cannot resolve a path to a module that does exist
Unable to resolve path to module 'react'. import/no-unresolved
import/no-unresolved fails when eslint-plugin-import cannot find the file or package on disk with its resolver.
4 causes, each with a fixWeb apps
ESLint reports no-unused-vars for React components and imports that are used
no-unused-vars reported for a component that is rendered as a JSX tag
ESLint's core no-unused-vars does not see variables used only as JSX tags, so a component imported and rendered as <Hello /> looks unused.
3 causes, each with a fixWeb apps
TypeScript rejects MUI Data Grid columns that set a type
A TypeScript error inside a column's renderCell callback
A columns array declared without a type is inferred with type as a plain string, which the Data Grid's column type union does not accept.
2 causes, each with a fix