TypeScript error: Object is possibly 'null'

Nextjs·Sep 12, 2026·beginner·
Quick answer

TypeScript's strict null checks flag any value that could be `null` before you use it. Narrow the type first with an `if` check, optional chaining (`?.`), or a non-null assertion (`!`) only when you're certain the value can't actually be null at that point.

What causes this error

With strictNullChecks enabled (on by default in strict mode), TypeScript tracks every place a value's type includes null and refuses to let you access a property on it until you've proven it isn't null in that branch of code.

The Fix

const el = document.getElementById('app');

// Wrong — TypeScript doesn't know el isn't null here
el.textContent = 'Hello';

// Fix 1: narrow with a check
if (el) {
  el.textContent = 'Hello';
}

// Fix 2: optional chaining (skips the line if el is null)
el?.textContent = 'Hello'; // note: optional chaining isn't valid on the left of an assignment — use Fix 1 or Fix 3 for writes

// Fix 3: non-null assertion — only when you're certain
el!.textContent = 'Hello';

Common causes / variations

  • DOM queries like document.getElementById, which always return a nullable type
  • Optional object properties or function parameters typed with | null
  • Overusing the ! assertion instead of actually narrowing — this silences the checker without fixing the underlying risk

Related errors

See also: Property does not exist on type 'never'.

Was this fix helpful?

Comments

Loading comments...

Fix: TypeScript Object is possibly 'null' | BugFixer | BugFixer