0 day streak
javascript / intermediate
Snippet

Dynamic Object Validation with Proxies

The Proxy object allows you to create a wrapper for another object, intercepting fundamental operations like property access and assignment. This is ideal for schema validation or logging without modifying the original object logic.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const validator = {
set: (target, prop, value) => {
if (prop === 'score') {
if (!Number.isInteger(value)) throw new TypeError('Score must be an integer');
if (value < 0) throw new RangeError('Score cannot be negative');
}
target[prop] = value;
return true;
}
};
const gameState = new Proxy({}, validator);
gameState.score = 10; // Valid
// gameState.score = -5; // Throws RangeError
nodejs
Breakdown
1
set: (target, prop, value) => { ... }
A trap for setting property values on the target object.
2
target[prop] = value;
Applies the validated value to the original object.
3
new Proxy({}, validator);
Creates the proxy with an empty target and the defined validation rules.