This is by no means a fail safe solution, use with care, and add to the exceptions object anything that you can't avoid.
Created
January 5, 2022 17:53
-
-
Save vhoyer/f5e1d653393ac7c15ae7f50d00b07272 to your computer and use it in GitHub Desktop.
Proxy Handler for accessing deep properties arbitrarily, like `obj.a.b.c.d.e` without getting the `cannot access a of undefined`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const exceptions = { | |
// map: () => {}, | |
}; | |
const handler = { | |
get(target, key) { | |
if (key === Symbol.toPrimitive) return () => undefined; | |
if (!Object.keys(target).includes(key)) { | |
const proxy = new Proxy(exceptions, handler); | |
proxy.object = () => key; | |
return proxy; | |
} | |
return target[key]; | |
}, | |
} | |
export default new Proxy({}, handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment