Skip to content

Proxy Pattern ​

proxyPattern.ts ​

ts
// type Human = { firstName: string; lastName: string };
const human = { firstName: "John", lastName: "Doe" };

const humanHandler: ProxyHandler<typeof human> = {
  get(target: typeof human, prop: keyof typeof human): string {
    if (prop === "firstName") {
      return target[prop].toLowerCase();
    }
    if (prop === "lastName") {
      return target[prop].toUpperCase();
    }
    return target[prop];
  },
  set(target: typeof human, prop: keyof typeof human, value: string): boolean {
    target[prop] = value.replace(/[aeiou]/gi, "");
    return true;
  }
};

const humanProxy = new Proxy(human, humanHandler);

console.log(humanProxy.lastName); // DOE
humanProxy.firstName = "Jane";
console.log(humanProxy.firstName); // jn

Released under the MIT License.