TypeScript says e.target.files is possibly null in a file input
Object is possibly 'null'.Short answer
With strictNullChecks on, TypeScript types files on an input as possibly null, so reading files[0] directly is an error. Narrow the value first with an if check, which is the safe fix, or use optional chaining. Use the non-null assertion only when you are sure a file exists, because it removes the check without changing runtime behaviour.
Fix it fast
1Find out which cause you have
Check whether strictNullChecks is on. With it on, null has its own type and using it where a value is expected is an error.
grep -n "strict" tsconfig.json2Match what you see, then jump to its fix
- 1
Object is possibly 'null' on the line that reads filesfiles is read without checking that it existsFix - 2
Same error, in a handler where no file simply means do nothing.Optional chaining is a shorter fix when a missing file is fineFix - 3
A file was already required by validation before this handler runs.You are sure a file exists and want to skip the checkFix
- 1
What does the error look like?
Object is possibly 'null'.Object is possibly 'null' on e.target.files[0]
Cause 1 of 3
files is read without checking that it exists
1Check
MDN says files is null when the input is not of type file, and a file input returns an empty FileList when nothing is selected. TypeScript's type covers both, so it includes null. Find the handler that indexes files directly.
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files[0];
};2Fix
Narrow with a check, the same way the TypeScript handbook narrows a possibly null value, and return early when nothing was chosen.
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0) return;
const file = files[0];
upload(file);
};3Verify
Run the compiler; the error should be gone.
npx tsc --noEmitConfirmed by typescriptlang.org
Cause 2 of 3
Optional chaining is a shorter fix when a missing file is fine
1Check
The handbook shows optional chaining as a safe alternative to an explicit check. The result then can be undefined, so the next line must handle that.
grep -rn "files\[0\]" src/2Fix
Use ?. and handle the undefined result.
const file = e.target.files?.[0];
if (file) upload(file);3Verify
Compile again; hovering file should show File | undefined.
npx tsc --noEmitConfirmed by typescriptlang.org
Cause 3 of 3
You are sure a file exists and want to skip the check
1Check
The non-null assertion removes null from the type without checking anything at runtime.
grep -rn "files!" src/2Fix
Write ! after the expression only when the value cannot be null. If it can, you get a runtime TypeError instead of a compile error.
const file = e.target.files![0];3Verify
Compile, then run the handler once with no file chosen to see whether it can ever happen.
npx tsc --noEmitConfirmed by typescriptlang.org
How do I stop it coming back?
- Keep strictNullChecks on and handle the empty selection with a code path.
- Prefer narrowing over ! so the empty case has a code path.
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 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 fixWeb apps
The renderInput prop stopped working on the MUI X DatePicker
The custom TextField (variant, size, helperText) is ignored
renderInput was removed from the MUI X date pickers in version 6.
3 causes, each with a fix