← Back to Error Lab

TypeScript: Object is possibly 'null' or 'undefined'

Published 2026-04-20

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

When the `strictNullChecks` flag is enabled in `tsconfig.json` (which is highly recommended), TypeScript assumes that objects can potentially be `null` or `undefined` based on their type definitions. If an API call returns `User | null`, or if you query the DOM (`document.getElementById` returns `HTMLElement | null`), TypeScript will prevent you from accessing properties on that object until you explicitly prove to the compiler that the object actually exists at runtime. This prevents the JavaScript 'Cannot read property of undefined' error from occurring in production.

Fix / Solution

You must narrow the type. The most common way is an `if (obj !== null)` check, which tells the TypeScript compiler it is safe to proceed. Alternatively, use optional chaining (`?.`) if you just want to safely return undefined. If you are 100% mathematically certain the object exists (e.g., a static DOM element), you can use the non-null assertion operator (`!`), though this bypasses type safety and should be used sparingly.

Code Snippet

// ❌ TypeScript Error: Object is possibly 'null'
const el = document.getElementById('app');
el.innerHTML = 'Hello';

// ✅ Fix 1: Type narrowing via if-statement
const el = document.getElementById('app');
if (el) {
  el.innerHTML = 'Hello';
}

// ✅ Fix 2: Non-null assertion (Use only if absolutely certain)
const el = document.getElementById('app')!;
el.innerHTML = 'Hello';