Proxy Design Pattern in TS
This blog is my knowledge dump. For more structured blogs visit: https://medium.com/@ArcadeBuilds
act as an intermediary between two parties.
new Proxyhelps use create the proxy in TS, it has params, the target & the handlers.Reflectcan also be used instead of direct property access in objects (obj[“name”])
Full code
const person = {
name: "Ben",
age: 20,
gender: "male",
};
const proxyPerson = new Proxy(person, {
get(target, p) {
if (p === "gender") {
console.log("Gender is not accessible");
} else {
return Reflect.get(target, p);
}
},
set(target, p, newValue) {
if (p === "age") {
if (newValue < 18 || newValue > 50) {
console.log("Age must be in range of 18 & 50");
return false;
} else {
Reflect.set(target, p, newValue);
}
} else {
Reflect.set(target, p, newValue);
}
return true;
},
});
console.log(proxyPerson.gender);
proxyPerson.age = 15; // this will give the error
console.log(proxyPerson.age);