Skip to content

strictNullChecks: possibly null value

Quick summary

Your variable has type T | null but you used it as if it were T — TypeScript blocks this under strict null checks.

Why this happens

  • A function returns T | null but the caller uses the result without a null check

  • An optional property (prop?: T) is accessed without checking for undefined first

  • A DOM query like document.getElementById returns HTMLElement | null but is used directly

Minimal example

✗ Broken code
function getElement(id: string) {
  const el = document.getElementById(id); // HTMLElement | null
  return el.innerHTML; // error: Object is possibly null
}
✓ Fixed code
function getElement(id: string) {
  const el = document.getElementById(id);
  return el?.innerHTML ?? ''; // safe access with fallback
}

Using optional chaining (?.) and nullish coalescing (??) safely handles the null case without suppressing the type check.

How to diagnose

  • Read the TS error: 'Object is possibly null or undefined' and note the variable and line

  • Check the type signature of the source — does it include null or undefined in the return type?

  • Use a type guard (if (x !== null)) to narrow the type before accessing properties

How to fix

  • Add a null check before using the value: if (value !== null) { /* use value */ }

  • Use the non-null assertion operator (!) only if you are certain the value is not null: value!.prop

  • Provide a default value with the nullish coalescing operator: (value ?? defaultValue).prop

How to prevent

  • Always handle null and undefined cases explicitly — do not use ! to suppress the error without certainty

  • Use optional chaining (?.) for safe property access on possibly-null values: value?.prop

Related Resources

Related Glossary

Related Lessons

← Back to language