TypeScript: Object Is PossiblyNull or Undefined — Fixed [2026]
Also covers: optional chaining · nullish coalescing · type guards · non-null assertion · DOM null · strictNullChecks
⚡ The Error
Object is possibly 'null'.
// OR:
Object is possibly 'undefined'.
// OR:
Cannot invoke an object which is possibly 'undefined'.✅ Fastest Fix — optional chaining
// ❌ Error: Object is possibly 'undefined'
const city = user.address.city
// ✅ Fix — optional chaining
const city = user?.address?.city // string | undefined — safeWhy 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.
Optional Chaining (?.) for Safe Property Access
Most common fix — chain of property accessestype 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/undefinedNullish Coalescing (??) for Default Values
Provide a fallback when value is null/undefinedconst 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"
}Type Guard with if Check
Best for complex logic after the null checkAn if check narrows the type inside the block — TypeScript knows the value is not null/undefined after the guard.
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(", ")
}Non-Null Assertion Operator (!)
Use sparingly — only when you are 100% certainThe ! operator tells TypeScript a value is definitely not null or undefined. It provides zero runtime safety — if you are wrong, the app crashes.
// ✅ 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 UserThe ! 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.
Fix DOM Element Possibly Null
document.getElementById() · querySelector()DOM query methods return Element | null. TypeScript requires you to handle the null case before accessing element properties.
// 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 renderPrevention
- Use optional chaining (?.) as the default for nullable property access — it is always safe
- Use nullish coalescing (??) not || when the value could legitimately be 0, false, or empty string
- Prefer early-return guards (if (!x) return) over nested null checks for readability
- Use useRef<T>(null) in React instead of getElementById — refs are typed and integrate with TypeScript
- Reserve ! for values you have genuinely verified elsewhere — document its reason with a comment
- Never disable strictNullChecks — it prevents real runtime crashes
Frequently Asked Questions
Why does TypeScript say 'Object is possibly null or undefined'?+−
What is optional chaining (?.) in TypeScript?+−
What is the difference between ?. and ! in TypeScript?+−
What is nullish coalescing (??) vs OR (||) in TypeScript?+−
How do I handle null from document.getElementById()?+−
Should I disable strictNullChecks to avoid these errors?+−
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