Skip to main content
TS2531

Object is possibly 'null'.

You're using a value that TypeScript knows can be null.

Related compiler flag: strictNullChecks

What it means

With strictNullChecks on, null is no longer assignable to every type — it's tracked separately. If a value's type includes null, you must handle that case before using it.

This error is doing real work: it's the class of bug that produces Cannot read properties of null at runtime. Every one you fix is a crash you don't ship.

Reproduce it

const el = document.getElementById("app");
el.innerHTML = "hi";
// ~~ Object is possibly 'null'.

How to fix it

Guard and handle the null case

Almost always. Decide what should happen when it's null — that decision is the point of the error.

Before
const el = document.getElementById("app");
el.innerHTML = "hi";
After
const el = document.getElementById("app");
if (!el) throw new Error("#app not found");
el.innerHTML = "hi";

Optional chaining

Doing nothing when the value is null is genuinely acceptable.

Before
el.innerHTML = "hi";
After
if (el) el.innerHTML = "hi";
// or: el?.setAttribute("hidden", "");

Non-null assertion (!) — use sparingly

You can prove it's non-null from context the compiler can't see (e.g. an element you just created). It silences the check without any runtime protection: if you're wrong, you get the exact crash the error was warning about.

Before
const el = document.getElementById("app");
After
const el = document.getElementById("app")!; // asserts non-null

Suppressing it

Prefer a real guard. A ! is a promise to the compiler that you're right — and it's unchecked, so a wrong ! produces exactly the null-dereference crash strictNullChecks exists to prevent.

Related errors

Hitting this while migrating to TypeScript?

Convert JavaScript to TypeScript deterministically — imports rewritten, JSDoc promoted to real types, class fields declared. No guessed types.

Open the converter