TS2533

error TS2533: Object is possibly ‘null’ or ‘undefined’.

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
11
type Person = {
address?: {
street: string;
zipCode: number;
} | null
name: string;
}

function logStreet(person: Person): void {
console.log(person.address.street);
}

Fixed Code ✔️

The error originates from the fact that address can be undefined (because of the ?) or null. To fix the problem, we can check if address is defined by using optional chaining:

1
2
3
4
5
6
7
8
9
10
11
type Person = {
address?: {
street: string;
zipCode: number;
} | null
name: string;
}

function logStreet(person: Person): void {
console.log(person.address?.street);
}