javascript / intermediate
Snippet
Dynamic Validation with Proxy
The Proxy object allows you to intercept and redefine fundamental operations for an object, such as property assignment. This is ideal for runtime type checking and validation logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const userSchema = {set(target, prop, value) {if (prop === 'age' && (typeof value !== 'number' || value < 0)) {throw new TypeError('Age must be a positive number');}target[prop] = value;return true;}};const user = new Proxy({}, userSchema);
nodejs
Breakdown
1
set(target, prop, value)
A trap for setting property values on the target object.
2
new Proxy({}, userSchema)
Wraps a plain object with the validation handler.