Last active
February 22, 2019 10:12
-
-
Save julien-f/61827255c9d9b83655bd15c9978c8ac1 to your computer and use it in GitHub Desktop.
Error when accessing missing properties
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
class MissingPropertyAccess extends TypeError { | |
get name() { | |
return this.constructor.name; | |
} | |
constructor(object, property) { | |
super(`access to missing property ${String(property)}`); | |
this.object = object; | |
this.property = property; | |
} | |
} | |
const traps = { | |
get(target, property) { | |
if (property in target) { | |
return target[property]; | |
} | |
throw new MissingPropertyAccess(target, property); | |
} | |
}; | |
export const definitely = obj => new Proxy(obj, traps); | |
const deepTraps = { | |
get(target, property) { | |
if (property in target) { | |
const value = target[property]; | |
return value !== null && typeof value === "object" | |
? definitelyDeep(value) | |
: value; | |
} | |
throw new MissingPropertyAccess(target, property); | |
} | |
}; | |
export const definitelyDeep = obj => new Proxy(obj, deepTraps); | |
export { definitely as default} | |
definitely.deep = definitelyDeep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment