javascript - Nesne muhtemelen 'null'


Bir nesnenin null olup olmadığını kontrol etmek istiyorum, yapıyor

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

ama bu hatayı alıyorum:

 error TS2531: Object is possibly 'null'.

Cevap #1

Bu hatayı almanızın nedeni, nesneniz bir dizi değil, null olduğunda bir dizinin bir öğesine erişmeye çalışmanızdır. Kontrolünüz temelde null[0] !== null demektir.

Sourabh Somani'nin önerdiği gibi, nesnenin 'falsey' olmadığını kontrol etmek sorunu çözmelidir

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

Bir 'falsey' kontrolü, nesnenizin örneğin sahte bir değer olup olmadığını belirleyecektir:

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

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

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