capypad
0 day streak
javascript / expert
Snippet

Structural Validation with Proxy Traps

The Proxy object allows you to create a wrapper for another object, intercepting fundamental operations like property assignment. By using the 'set' trap and 'Reflect' API, you can implement robust runtime type checking.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const schema = { name: 'string', age: 'number' };
const handler = {
set(target, prop, value) {
if (schema[prop] && typeof value !== schema[prop]) {
throw new TypeError(`Invalid type for ${prop}`);
}
return Reflect.set(...arguments);
}
};
 
const user = new Proxy({}, handler);
user.name = 'Alice'; // Works
user.age = 'none'; // Throws TypeError
Breakdown
1
set(target, prop, value)
A trap for setting property values on the proxy object.
2
Reflect.set(...arguments)
Standard way to perform the default action of assigning a value to a property.
3
new Proxy({}, handler)
Constructs a proxy that uses the defined handler to intercept operations.