Sandro Rey
Sandro Rey

Reputation: 2999

Object is possibly 'null'

I want to check if an object is null,doing

let hostels = null;
if (hostels[0] !== null && hostels[0].name !== null) {
}

but I have this error:

 error TS2531: Object is possibly 'null'.

Upvotes: 2

Views: 221

Answers (1)

Darren Lamb
Darren Lamb

Reputation: 1563

You are getting this error is because you are trying to access an element of an array when your object is not an array, it is null. Your check is essentially saying null[0] !== null

As Sourabh Somani suggested, checking that the object is not 'falsey' should resolve the issue

let hostels = null;
if (hostels && hostels[0] !== null && hostels[0].name !== null) {
}

A 'falsey' check will determine if your object is a false value for example:

let hostels = null;
if(hostels) {  } // false

let hostels = undefined;
if(hostels) { } // false 

let hostels = [];
if(hostels) { } // true

Upvotes: 1

Related Questions