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()returnsHTMLElement | nullArray.find()returnsT | undefined- Optional function parameters
- API responses with nullable fields
Map.get()returnsT | 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>;
Related resources
How to prevent it
- Keep
strict: truein tsconfig β donβt disablestrictNullChecksto make errors go away - Design your types to be explicit about nullability:
name: stringvsname: 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
Related: What is TypeScript