How to fix "Object is possibly null" TypeScript error

TypeScript throws an error when I try to access a property or call a method:

error TS2531: Object is possibly 'null'.

For example, when reading from the DOM or from an API response:

const input = document.getElementById('username')
console.log(input.value) // Error: Object is possibly 'null'

How do I fix this without just casting to any?

Solution

document.getElementById returns HTMLElement | null because the element might not exist in the DOM. TypeScript correctly warns you about this.

The cleanest fix is an explicit null check before accessing the value:

const input = document.getElementById('username')

if (input instanceof HTMLInputElement) {
  console.log(input.value) // safe, TypeScript knows it's HTMLInputElement
}

For optional chaining when you just want to read a value and get undefined instead of crashing:

const value = (document.getElementById('username') as HTMLInputElement)?.value
Alternative #1

Optional chaining (?.) lets you access deeply nested properties without a chain of null checks. If any value in the chain is null or undefined, the expression short-circuits and returns undefined:

const user = getUser() // returns User | null

// Without optional chaining:
const city = user !== null ? user.address.city : undefined

// With optional chaining:
const city = user?.address?.city

It also works for method calls:

const result = user?.getName()?.toUpperCase()
Alternative #2

The nullish coalescing operator (??) pairs well with optional chaining to provide a fallback value when the result is null or undefined:

const username = user?.name ?? 'Anonymous'
const count = data?.items?.length ?? 0

Unlike the || operator, ?? only falls back for null and undefined, not for falsy values like 0 or empty string. This makes it safer for numeric and boolean fields.

Alternative #3

The non-null assertion operator (!) tells TypeScript to trust that the value is not null. Use it only when you are certain, for example when you control the HTML and know the element always exists:

const input = document.getElementById('username') as HTMLInputElement
console.log(input!.value)

Avoid using ! as a reflexive fix. It silences the TypeScript error without fixing the underlying problem, so if the value ever is null at runtime, your app will throw an uncaught error.

Last modified: April 16, 2026
Stay in the loop
Subscribe to our newsletter to get the latest articles delivered to your inbox