ProjectStack
typescript

TS2531: Object is possibly 'null'

TypeScript's strict null checks are on and you're trying to access a property or call a method on a value that could be null. Before using it, you need to confirm the value isn't null at that point in the code.

Common causes

  • Using document.getElementById() or similar DOM methods that return Element | null
  • A function returns Type | null but you're using the result without checking for null
  • A conditional assignment that may not set the variable in all branches
  • Optional chaining hasn't been applied to a nullable value in the chain

How to fix it

  1. Add a null check before accessing: if (element !== null) { element.value }
  2. Use optional chaining to safely access: element?.value
  3. Use the non-null assertion operator if you're certain it won't be null: element!.value — use sparingly
  4. Provide a fallback with nullish coalescing: element ?? defaultElement

Example

const input = document.getElementById('username'); input.focus(); // error TS2531: Object is possibly 'null'.

Calling a method on a DOM element returned by getElementById, which can return null

Browse more errors

The Developer Hub covers 150+ errors across Git, npm, Node.js, Python, TypeScript, and Docker — with plain-English explanations and fix steps.