TS2531
Object is possibly 'null'.
Broken Code ❌
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:
type Person = {
address: {
street: string;
zipCode: number;
} | null;
name: string;
};
function logStreet(person: Person): void {
console.log(person.address?.street);
}