Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Created January 31, 2020 16:32
Show Gist options
  • Select an option

  • Save r3dm1ke/626f036cd6daedcf8f0e6df6f7241672 to your computer and use it in GitHub Desktop.

Select an option

Save r3dm1ke/626f036cd6daedcf8f0e6df6f7241672 to your computer and use it in GitHub Desktop.
Using Proxy API to define custom validation for property values
const stringValidatorHandler = {
set: (obj, key, value) => {
if (typeof value !== 'string') {
throw new Error('Expected string!')
}
obj[key] = value.toUpperCase();
}
}
const weirdObject = new Proxy({}, stringValidatorHandler);
weirdObject.a = 5 // Error: Expected string!
weirdObject.a = 'abacaba';
console.log(weirdObject.a); // ABACABA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment