我制作了这个功能,它可以用作打字稿版本 <3.7 的安全导航运算符的替代品
/*
This function is to validate if Object is accessible or not as well as returns its value if it is accessible.
it will return false if Object is not accessible (if value is null or undefined)
If Object is accessible then it will return its value.
Example: if I want to check that is "obj.key1.key2" is accessible and I want to put check on its value.
if (isAccessible(obj,["key1","key2"]) == some_value){
...do something...
}
no need to check for null and undefined for each key.
NOTE: this function is alternate of "SAFE NAVIGATOR OPERATOR (?)" of typescript which is not supported in versions <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);
}
}
}