TypeScriptNull SafetyError Fix2026 Updated

TypeScript: Object Is PossiblyNull or Undefined — Fixed [2026]

Also covers: optional chaining · nullish coalescing · type guards · non-null assertion · DOM null · strictNullChecks

January 20266 min readTypeScript 5.x · strict mode

⚡ The Error

Error
Object is possibly 'null'.
// OR:
Object is possibly 'undefined'.
// OR:
Cannot invoke an object which is possibly 'undefined'.

✅ Fastest Fix — optional chaining

Use ?. for safe property access
// ❌ Error: Object is possibly 'undefined'
const city = user.address.city

// ✅ Fix — optional chaining
const city = user?.address?.city   // string | undefined — safe

Why TypeScript Reports 'Possibly Null or Undefined'

TypeScript with strictNullChecks (on by default in strict mode) tracks which values can be null or undefined . When you try to access a property on such a value without first checking it exists, TypeScript flags it — because if the value really is null at runtime, you get a crash.

This is TypeScript protecting you from the most common JavaScript runtime error: Cannot read properties of null . The fix is always to handle the null/undefined case explicitly.

1

Optional Chaining (?.) for Safe Property Access

Most common fix — chain of property accesses
1 min
Optional chaining patterns
type User = {
  name: string
  address?: {
    city?: string
    zip?: string
  }
}

function getUserCity(user: User | null): string | undefined {
  // ❌ Error: Object is possibly 'null'
  // return user.address.city

  // ✅ Optional chaining — returns undefined if any link is null/undefined
  return user?.address?.city
}

// Optional chaining with method calls
const length = str?.trim()?.length    // undefined if str is null/undefined

// Optional chaining with array index
const first = arr?.[0]                // undefined if arr is null/undefined

// Optional chaining with function calls
const result = callback?.()           // undefined if callback is null/undefined
2

Nullish Coalescing (??) for Default Values

Provide a fallback when value is null/undefined
1 min
?? vs || — know the difference
const user = null
const name = user?.name ?? "Guest"    // "Guest" — ?? handles null/undefined

// ?? vs || — critical difference:
const count = 0
console.log(count ?? 10)   // 0  — ?? only triggers on null/undefined
console.log(count || 10)   // 10 — || triggers on ANY falsy (0, "", false)

// Real-world pattern — API response with default
interface Config { timeout?: number; retries?: number }

function getTimeout(config: Config): number {
  return config.timeout ?? 5000   // 5000ms default if timeout is undefined
}

// Chaining ?? with ?.
function getDisplayName(user: User | null): string {
  return user?.displayName ?? user?.name ?? "Anonymous"
}
3

Type Guard with if Check

Best for complex logic after the null check
2 min

An if check narrows the type inside the block — TypeScript knows the value is not null/undefined after the guard.

Type guard patterns
function processUser(user: User | null) {
  // Guard — TypeScript narrows to User inside the if block
  if (!user) {
    console.error("No user found")
    return
  }
  // Here TypeScript knows: user is User (not null)
  console.log(user.name.toUpperCase())
}

// Guard with early return (preferred pattern)
async function getProfile(id: string) {
  const user = await db.user.findUnique({ where: { id } })
  if (!user) throw new Error(`User ${id} not found`)

  // From here on, user is User — not null
  return { ...user, displayName: user.name.toUpperCase() }
}

// Truthiness guard for arrays and strings
function formatList(items: string[] | null): string {
  if (!items || items.length === 0) return "No items"
  return items.join(", ")
}
4

Non-Null Assertion Operator (!)

Use sparingly — only when you are 100% certain
1 min

The ! operator tells TypeScript a value is definitely not null or undefined. It provides zero runtime safety — if you are wrong, the app crashes.

Non-null assertion — use with care
// ✅ Acceptable — you have already verified the value exists
const users = [{ id: 1, name: "Alice" }]
const first = users[0]!   // safe — we know the array has one item

// ✅ Acceptable — DOM element that you know exists
const form = document.getElementById("signup-form")!
form.addEventListener("submit", handleSubmit)

// ❌ Bad — blindly asserting without evidence
const user = getUser()!   // crash at runtime if getUser() returns null
user.name.toUpperCase()

// Better alternative — use a guard
const user = getUser()
if (!user) throw new Error("User not found")
user.name.toUpperCase()   // safe — TypeScript narrowed to User

The ! operator is a code smell when used frequently. If you find yourself adding ! everywhere, the real issue is your type definitions need to reflect the actual shape of your data.

5

Fix DOM Element Possibly Null

document.getElementById() · querySelector()
2 min

DOM query methods return Element | null. TypeScript requires you to handle the null case before accessing element properties.

DOM null safety patterns
// document.getElementById returns HTMLElement | null
// document.querySelector returns Element | null

// ✅ Pattern 1 — type guard
const input = document.getElementById("username")
if (input) {
  input.focus()   // safe — TypeScript knows input is HTMLElement
}

// ✅ Pattern 2 — type assertion after guard
const input = document.getElementById("username") as HTMLInputElement | null
if (input) {
  console.log(input.value)   // HTMLInputElement has .value
}

// ✅ Pattern 3 — non-null assertion (only when element definitely exists)
const form = document.getElementById("main-form")!
const inputs = form.querySelectorAll("input")

// ✅ Pattern 4 — optional chaining for one-liners
const value = (document.getElementById("email") as HTMLInputElement)?.value ?? ""

// ✅ In React — use useRef instead of getElementById
import { useRef } from "react"
const inputRef = useRef<HTMLInputElement>(null)
// Later: inputRef.current?.focus()  // safely handles null on first render

Prevention

Frequently Asked Questions

Why does TypeScript say 'Object is possibly null or undefined'?+
TypeScript's strictNullChecks option (enabled by default in strict mode) makes null and undefined their own types. When a value could be null or undefined — from an API response, optional property, or DOM query — TypeScript prevents you from accessing its properties without first checking it is not null.
What is optional chaining (?.) in TypeScript?+
Optional chaining (?.) safely accesses a property or method on a value that might be null or undefined. If the value is null or undefined, the expression short-circuits and returns undefined instead of throwing a runtime error. Example: user?.address?.city returns undefined instead of crashing if user or address is null.
What is the difference between ?. and ! in TypeScript?+
?. (optional chaining) safely handles null/undefined by returning undefined. ! (non-null assertion) tells TypeScript to trust you that the value is not null/undefined — it does not add any runtime safety. If you use ! on a null value, you still get a runtime error. Prefer ?. for safe access; use ! only when you are absolutely certain.
What is nullish coalescing (??) vs OR (||) in TypeScript?+
?? returns the right side only when the left side is null or undefined. || returns the right side for any falsy value — including 0, empty string, and false. Use ?? when 0 or empty string are valid values you want to keep. Use || only when all falsy values should fall back to the default.
How do I handle null from document.getElementById()?+
document.getElementById() returns HTMLElement | null. Type guard with an if check, use non-null assertion (!) only if you know the element exists, or use a type assertion after the check: const el = document.getElementById('id') as HTMLInputElement.
Should I disable strictNullChecks to avoid these errors?+
No. strictNullChecks prevents real runtime crashes — 'Cannot read properties of null' is one of the most common JavaScript errors. Disabling it removes the protection. Fix the errors properly with null checks, optional chaining, or default values.

Need Expert Help?

We Write Type-Safe TypeScript from Day One

Softplix engineers use strict TypeScript with proper null handling — no ! everywhere, no any. Need help with your codebase? Let us help.

Talk to an Engineer