Skip to content

Object is possibly 'null' or 'undefined'

Error message

                Object is possibly 'null'
              

Quick summary

With strictNullChecks enabled, TypeScript prevents you from accessing properties on values that could be null or undefined without checking first.

Why this happens

  • Accessing a property on a variable typed as T | null

  • Using an optional property without checking for undefined

  • A function returns T | null and the result is used without a null check

  • A DOM element lookup (getElementById) returns T | null

Minimal example

✗ Broken code
function getName(user: { name: string } | null): string {
  return user.name; // possibly null
}
✓ Fixed code
function getName(user: { name: string } | null): string {
  return user?.name ?? "unknown";
}

Use optional chaining and nullish coalescing to safely handle null.

How to diagnose

  • Check if the variable is typed with | null or | undefined

  • Look for optional properties (with ?) that could be undefined

  • Check if the value comes from a function that can return null

How to fix

  • Add a null check: if (value !== null) { ... }

  • Use optional chaining: value?.property

  • Use nullish coalescing: value ?? defaultValue

  • Use a non-null assertion: value!.property (only when you're certain)

How to prevent

  • Always enable strictNullChecks (part of strict mode)

  • Use optional chaining and nullish coalescing for nullable values

  • Design APIs to avoid returning null where possible

Related Resources

← Back to language