TS2532

error TS2532: Object is possibly ‘undefined’.

Broken Code ❌

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
type Person = {
age: number;
};

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

Alternatively, we can use optional chaining:

1
2
3
4
5
6
7
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.