Skip to content

Instantly share code, notes, and snippets.

@iainjreid
Last active February 17, 2020 12:55
Show Gist options
  • Save iainjreid/4ea9fd166c76456a419a6afbf0d2f771 to your computer and use it in GitHub Desktop.
Save iainjreid/4ea9fd166c76456a419a6afbf0d2f771 to your computer and use it in GitHub Desktop.
Property validation using a JavaScript Proxy
const shape = new Proxy({}, {
set: (obj, prop, value) => {
if (prop === 'sides') {
if (!(value > 0)) {
throw Error('Property "sides" must be greater than zero');
}
}
// Set the value
obj[prop] = value;
// Return success
return true
}
});
shape.sides = 4; // Works - 4
shape.sides = 0; // Error - Property "sides" must be greater than zero
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment