Skip to content
Latchkey

TS2531: Object is possibly null - in CI

Under strictNullChecks, you used a value whose type includes null without first ruling that out.

What this error means

Type-checking fails with TS2531 at a member access or call on a value that can be null (e.g. a DOM query result).

tsc
src/dom.ts(4,1): error TS2531: Object is possibly 'null'.

Common causes

How to fix it

Guard before use

  1. Check for null, or use optional chaining for member access
ts
const el = document.getElementById("app")
if (el) el.classList.add("ready")

Assert non-null only when guaranteed

  1. Use the non-null assertion (!) only when you can prove the value is present
ts
const el = document.getElementById("app")!

How to prevent it

  • Keep strictNullChecks on and handle nullable values with guards or optional chaining instead of assertions.

Frequently asked questions

What causes "TS2531 object possibly null"?
Type-checking fails with TS2531 at a member access or call on a value that can be null (e.g. a DOM query result).
How do I fix TS2531 object possibly null?
Guard before use

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card