TS2531

error TS2531: Object is possibly ‘null’.

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 null. To fix the problem, we can check if address is null 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);
}