🔧 Error Fixes
· 2 min read
Last updated on

TypeScript: Object Is Possibly Null — How to Fix It


Object is possibly 'null'
Object is possibly 'undefined'

What causes this

TypeScript’s strictNullChecks (enabled by default with strict: true) prevents you from using a value that might be null or undefined without checking first. This catches real bugs — accessing a property on null crashes at runtime.

Common triggers:

  • document.getElementById() returns HTMLElement | null
  • Array.find() returns T | undefined
  • Optional function parameters
  • API responses with nullable fields
  • Map.get() returns T | undefined

Fix 1: Null check with if statement

const el = document.getElementById('app');

// ❌ Object is possibly 'null'
el.innerHTML = 'Hello';

// ✅ Check first
if (el) {
  el.innerHTML = 'Hello';
}

// ✅ Or with early return
if (!el) throw new Error('Element #app not found');
el.innerHTML = 'Hello';

Fix 2: Optional chaining

When you want to silently skip if null:

// ✅ Does nothing if el is null
el?.classList.add('active');
el?.setAttribute('data-loaded', 'true');

// ✅ Nested optional chaining
const name = user?.profile?.displayName;

Fix 3: Nullish coalescing for defaults

// ✅ Use a default value when null/undefined
const name = user?.name ?? 'Anonymous';
const port = config.port ?? 3000;
const items = response.data ?? [];

Fix 4: Non-null assertion (use sparingly)

When you’re 100% certain the value isn’t null:

// The ! tells TypeScript "trust me, this isn't null"
const el = document.getElementById('app')!;
el.innerHTML = 'Hello';

⚠️ Only use ! when you genuinely know it can’t be null. If you’re wrong, you get a runtime crash — exactly what TypeScript was trying to prevent.

Fix 5: Type narrowing with typeof

function process(value: string | null | undefined) {
  // ❌ Object is possibly null/undefined
  console.log(value.toUpperCase());

  // ✅ Type narrowing
  if (typeof value === 'string') {
    console.log(value.toUpperCase()); // TypeScript knows it's a string here
  }
}

Fix 6: Use the satisfies operator for complex cases

// When you need to assert a type while keeping inference
const config = {
  port: process.env.PORT ?? '3000',
  host: process.env.HOST ?? 'localhost',
} satisfies Record<string, string>;

How to prevent it

  • Keep strict: true in tsconfig — don’t disable strictNullChecks to make errors go away
  • Design your types to be explicit about nullability: name: string vs name: string | null
  • Use optional chaining (?.) and nullish coalescing (??) as your default patterns
  • Initialize variables with proper defaults instead of leaving them as undefined
  • Prefer early returns (if (!x) return) over deeply nested null checks