Skip to main content

Command Palette

Search for a command to run...

Proxy Design Pattern in TS

Published
•1 min read•View as Markdown
A

This blog is my knowledge dump. For more structured blogs visit: https://medium.com/@ArcadeBuilds

  • act as an intermediary between two parties.

  • new Proxy helps use create the proxy in TS, it has params, the target & the handlers.

  • Reflect can 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);

More from this blog

A

Aashish's Blog

15 posts

This is my knowledge dump. For more structured blogs visit: https://medium.com/@ArcadeBuilds