How can i fix 'object is possibly 'null' or 'undefined' in typescript?

This error surfaces when trying to access properties or methods on a value that could be `null` or `undefined`.

Example:


let user: { name?: string } | null = null;
console.log(user.name);

Solution:


let user: { name?: string } | null = null;
console.log(user?.name);
Use optional chaining (`?.`) to safely access properties and methods.

Beginner's Guide to TypeScript