In order to avoid error when accessing deeply nested properties, I wrote a proxy-returning function:
const safe_access = obj =>
new Proxy(obj, {
get: (o, k) =>
o[k] == null
? safe_access({})
: typeof o[k] === 'object'
? safe_access(o[k])
: o[k] });
Here's an example:
const a = safe_access({});
a.x.y.z; // no TypeError
However in its current form safe_access
is unable to tell when it has reached the end of the path. Meaning that it cannot return undefined
to signify that the property truly doesn't exist. This also means that you cannot have default values:
const a = safe_access({});
a.x.y.z || 42; // not 42
const {x: {y: {z = 42}}} = a;
z; // not 42
How can my proxy object detect the end of a property lookup?