In TypeScript versions prior to 3.7, I have created a custom function that can serve as an alternative to the safe navigation operator.
/*
This function is designed to check if an object is accessible and return its value if it is.
It returns false if the object is not accessible (i.e., if the value is null or undefined).
For example, if you want to verify if "obj.key1.key2" is accessible and perform a value check:
if (isAccessible(obj,["key1","key2"]) == some_value){
...do something...
}
You don't need to manually check for null and undefined at each key level.
NOTE: This function serves as an alternative to the "SAFE NAVIGATOR OPERATOR (?)" in TypeScript versions prior to 3.7
*/
isAccessible(data, keys, start=0) {
if (start == 0 && (data == null || data == undefined)) {
console.warn("data",data);
return data;
} else {
if (data[keys[start]] == null || data[keys[start]] == undefined) {
console.warn("Object valid till", keys.slice(0,start),keys[start],"undefined");
return data[keys[start]];
} else {
if (start + 1 >= keys.length) {
// console.log("output",data[keys[start]]);
return data[keys[start]];
}
return this.isAccessible(data[keys[start]], keys, start + 1);
}
}
}