tsc TS2531: Object is possibly 'null' in CI
TS2531 is the null counterpart of TS18048: a value whose type includes null is dereferenced without a guard. It appears most with DOM lookups like document.querySelector, which return T | null.
What this error means
tsc fails with "error TS2531: Object is possibly 'null'" at a property access or method call on a value that may be null.
tsc
src/dom.ts:3:1 - error TS2531: Object is possibly 'null'.
3 el.addEventListener('click', onClick);
~~Common causes
A nullable value is dereferenced without a check
document.getElementById and querySelector return Element | null. Using the result directly under strictNullChecks is an error.
strictNullChecks is on in CI but was off locally
The local tsconfig may have relaxed null checking, so the null path only surfaces when CI runs the stricter config.
How to fix it
Narrow out null before use
- Check the value for null before accessing it.
- Throw, return, or branch for the null case.
- Re-run tsc to confirm the dereference is safe.
src/dom.ts
const el = document.getElementById('app');
if (el === null) throw new Error('#app not found');
el.addEventListener('click', onClick);Use optional chaining for an optional effect
When doing nothing on null is fine, optional chaining expresses that without an assertion.
src/dom.ts
document.getElementById('app')?.addEventListener('click', onClick);How to prevent it
- Treat DOM and lookup results as nullable and guard them.
- Keep strict null settings identical across environments.
- Avoid
!non-null assertions on values that can really be null.
Related guides
tsc TS18048: 'x' is possibly 'undefined' (strictNullChecks) in CIFix tsc "error TS18048: 'x' is possibly 'undefined'" in CI - under strictNullChecks tsc requires a guard befo…
tsc TS2339: Property 'x' does not exist on type 'Y' in CIFix tsc "error TS2339: Property 'x' does not exist on type 'Y'" in CI - you accessed a member that is not dec…
tsc TS18046: 'x' is of type 'unknown' in CIFix tsc "error TS18046: 'x' is of type 'unknown'" in CI - under useUnknownInCatchVariables you used a caught…