Created
January 31, 2020 16:32
-
-
Save r3dm1ke/626f036cd6daedcf8f0e6df6f7241672 to your computer and use it in GitHub Desktop.
Using Proxy API to define custom validation for property values
This file contains hidden or 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 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