Skip to content
Latchkey

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

  1. Check the value for null before accessing it.
  2. Throw, return, or branch for the null case.
  3. 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →