Card 05/ 09
Proxy in the Wild: JavaScript's Proxy Object
The language builds proxies for you: a handler intercepts reads and writes on any object.
JavaScript, and so TypeScript, has the pattern built in: new Proxy(target, handler) returns an object that looks like target, and the handler's methods, called traps, run whenever a property is read, written or deleted. No class is needed and the target can be any object. This card uses one to log reads and refuse invalid writes on a settings object.
interface Settings {
theme: string;
fontSize: number;
}
const settings: Settings = { theme: "light", fontSize: 14 };
const guarded = new Proxy(settings, {
get(target, property, receiver) {
console.log(`read ${String(property)}`);
return Reflect.get(target, property, receiver);
},
set(target, property, value, receiver) {
if (property === "fontSize" && (typeof value !== "number" || value < 8)) {
console.log(`refused fontSize = ${value}`);
return true;
}
console.log(`write ${String(property)} = ${value}`);
return Reflect.set(target, property, value, receiver);
},
});
guarded.theme = "dark";
guarded.fontSize = 4;
console.log(`font size is ${guarded.fontSize}`);
console.log(`the original object: ${JSON.stringify(settings)}`);write theme = dark
refused fontSize = 4
read fontSize
font size is 14
the original object: {"theme":"dark","fontSize":14}The write of the theme passes through the set trap, is logged and is forwarded to the target with Reflect.set. The font size of 4 is refused, so the target keeps 14, as both the read through the proxy and the original object show. Reflect performs the default behaviour of each operation, which is how a trap forwards the call it has decided to allow.
This is a protection proxy in a few lines: it has the target.s interface, because it has every property the target has, and it decides which operations reach the target. Libraries use the same mechanism for change tracking, such as Vue's reactivity system, and for virtual objects whose properties are fetched only when read.
← → move through sections and cards