Object is possibly 'null' error in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Object is possibly 'null' error in TypeScript #

The error "Object is possibly 'null'" occurs when we try to access a property on an object that may have a value of null. To solve the error, use the optional chaining operator to short-circuit if the reference is equal to null, e.g. emp?.address?.country.

object is possibly null

Here is an example of how the error occurs.

index.ts
type Employee = { address: { country: string; city: string; } | null; // 👈️ could be null }; const emp: Employee = { address: null, }; // ⛔️ Error: Object is possibly 'null'.ts(2531) console.log(emp.address.country);

The address property on the Employee type could be null, which causes the error.

We can use the optional chaining (?.) operator to get around this.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: null, }; // ✅ No errors console.log(emp?.address?.country); // 👈️ using optional chaining

The question mark dot (?.) syntax is called optional chaining in TypeScript.

It is like using dot notation to access a nested property of an object, but instead of causing an error if the reference is nullish (null or undefined), it short-circuits returning undefined.

This approach is commonly used when fetching data from a remote API or reading data from a file, where some of the properties might not have a value.

An alternative approach is to use a simple if statement that serves as a type guard.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: null, }; // 👇️ check if not null or undefined if (emp.address != null) { console.log(emp.address.country); console.log(emp.address.city); }

We used an if statement to check if the emp.address property is not equal to null or undefined.

Once we enter the if block, TypeScript knows that the country and city properties are of type string.

Notice that we used loose not equals (!=), which checks for both null and undefined. You can exclusively check for null with strict not equals (!==).

The loose comparison covers both null and undefined because in a loose comparison null is equal to undefined.

index.ts
console.log(null == undefined); // 👉️ true console.log(null === undefined); // 👉️ false

You can also use the non-null assertion operator if you are sure the property could not have a value of null.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: { country: 'Germany', city: 'Hamburg', }, }; console.log(emp.address!.country); // 👉️ "Germany"

The exclamation mark is the non-null assertion operator in TypeScript.

It removes null and undefined from a type without doing any explicit type checking.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined.

We used it right after the address property, so we are telling TypeScript that emp.address will never have a value of null or undefined.

If you are making a comparison in an if statement, use the logical AND (&&) operator to make sure the property is of the correct type.

index.ts
type Employee = { address: { country: string; city: string; num?: number; } | null; }; const emp: Employee = { address: null, }; if ( emp.address && typeof emp.address.num === 'number' && emp.address.num > 50 ) { console.log('success'); }

The logical AND (&&) operator makes sure the address property is not null, that num exists on the address object and is a number before comparing it to the number 50.

This is needed because if the reference is nullish (null or undefined), the optional chaining operator (?.) will return undefined and TypeScript doesn't allow us to compare undefined to a number.

For example, this would fail:

index.ts
type Employee = { address: { country: string; city: string; num?: number; } | null; }; const emp: Employee = { address: null, }; // ⛔️ could be undefined, so not allowed if (emp?.address?.num > 50) { console.log('success'); }

The result might have a value of undefined because that's the return value of the optional chaining (?.) operator when it short-circuits. TypeScript won't allow us to compare a possibly undefined value to a number.

Another common way to avoid getting the error is to use the logical AND (&&) operator when accessing the property.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: null, }; if (emp.address && emp.address.country) { // 👉️ emp.address.country is type string here console.log(emp.address.country.toUpperCase()); }
The logical AND (&&) operator won't evaluate the value to the right if the value to the left is falsy (e.g null).

All of the values in the if condition have to be truthy for the if block to run.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are: undefined, null, false, 0, "" (empty string), NaN (not a number).

This is why TypeScript is able to infer the type of the emp.address.country property to be string in the if block.

An even better way to get around the "Object is possibly null" error in this situation is to use the typeof operator.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: null, }; if (emp.address && typeof emp.address.country === 'string') { // 👉️ emp.address.country is type string here console.log(emp.address.country.toUpperCase()); }

We explicitly check if the type of the country property is a string. This is better than checking if the value is truthy because empty strings are falsy values in JavaScript (and TypeScript).

Here is an example that illustrates why using typeof is better.

index.ts
type Employee = { address: { country: string; city: string; } | null; }; const emp: Employee = { address: { country: '', city: '', }, }; if (emp.address && emp.address.country) { const result = emp.address.country; console.log(result); } else { // 👉️ else block runs console.log('✅ This block runs'); }

The else block runs in the example.

The country property points to an empty string (falsy value), so just checking if the value is truthy might not be enough in your scenario.

It's always better to be explicit and use the typeof operator when possible. This helps us avoid some difficult to spot bugs.

Conclusion #

The "Object is possibly 'null'" error occurs when we try to access a property on an object that may have a value of null. To solve the error, use the optional chaining operator or a type guard to make sure the reference is not null before accessing properties.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.