TS2532

Object is possibly 'undefined'.

Broken Code ❌

type Person = {
  age: number;
};
 
function logAge(person?: Person): void {
  console.log(person.age);
}

Fixed Code ✔️

TypeScript warns us that person can be undefined (because of the ?). There are multiple ways to fix the problem. We can do an existence check using an if-condition:

type Person = {
  age: number;
};
 
function logAge(person?: Person): void {
  if (person) {
    console.log(person.age);
  }
}

Alternatively, we can use optional chaining:

type Person = {
  age: number;
};
 
function logAge(person?: Person): void {
  console.log(person?.age);
}

Optional chaining is less preferable in this case as it will log undefined if the person is undefined. Using the if-condition from the solution above, nothing will be logged to the console in case the person is undefined.

Suppressing the error

You can prevent the error by setting the value of "strictNullChecks" to false in the "compilerOptions" section of your "tsconfig.json" file.