Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone explain why this proxy behavior is not working on an enum?

export enum Status { Beginning, Middle, Ending }

export class MyClass {
  public status = new Proxy(Status, {
    set: (target, propertyKey, value) = {
      console.log('I have been set')
      return Reflect.set(target, propertyKey, value)
    },
    get: (target, propertyKey) => Reflect.get(target, propertyKey)
  })
}

Here's how I'm trying to use it:

let c = new MyClass
c.status = Status.Middle

However, attempting to set it results in the error message:

Type 'Status.Middle' is not assignable to type 'typeof Status'.

Answer №1

It seems like what you may actually need are accessors for the status property of MyClass, rather than a Proxy. Here's an example:

export enum Status { Beginning, Middle, Ending }

export class MyClass {
  private target: Status = Status.Beginning;

  public get status(): Status {
    return this.target;
  }
  public set status(status: Status) {
    console.log("I have been set");
    this.target = status;
  }
}

let c = new MyClass();
c.status = Status.Middle;
// logs "I have been set".

The main issue here is that if you want to intercept gets and sets on the status property of a MyClass instance, you should implement the behavior on MyClass itself, not on the Status enum. Also, using a full Proxy may be unnecessary if you only intend to wrap actions when working with a single property.

I hope this clarifies things for you. Best of luck!


If you find that using 'private' is not sufficient for your needs, you can try this alternative approach:

export class MyClass {
  status!: Status; // status will be defined in the constructor

  constructor() {
    let target = Status.Beginning;
    Object.defineProperty(this, 'status', {
      get() { return target; },
      set(status: Status) {
        console.log("I have been set");
        target = status;
      }
    })
  }
}

let c = new MyClass();
c.status = Status.Middle;
// logs "I have been set".

This method encapsulates the underlying target variable within a closure, making it completely inaccessible from outside the class. However, keep in mind that this creates a unique accessor for each instance of MyClass instead of utilizing a shared one on the prototype. Consider which approach suits your requirements best.

Good luck once more!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come code suggestion works flawlessly on Stackblitz, yet fails to function in Intellij?

Check out this GitHub repository for a simple way to reproduce the issue: https://github.com/tmtron/mathjs-typescript-types Successful Code Completion in Stackblitz Everything works perfectly when you open the project in Stackblitz: https://i.stack.imgur ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Setting up a Firebase app across multiple files using Node.js

Trying to organize my methods properly, I want to Initialize Firebase App in multiple files. However, I'm unsure of the best approach. Here is the structure of the file system: /functions |-keys |-methods | |-email.js | |-logger.js |-node_mod ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Using import statement is mandatory when loading ES Module in TS Node: server/src/index.ts

Attempting to kickstart a TypeScript Node project, I've gone ahead and added some essential dependencies (TypeScript, ESLint, Mongoose, and GraphQL). However, upon executing the command: ts-node-dev --respawn --transpile-only src/index.ts An error me ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

What is the best way to redirect before displaying a page in Next.js?

Is it possible to redirect a user before rendering a page in Next.js? Currently, my code looks like this: import { useRouter } from 'next/router'; export default function RedirectPage() { const router = useRouter(); router.push('/p ...

Explain the object type that is returned when a function accepts either an array of object keys or an object filled with string values

I've written a function called getParameters that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object ...

The app.html for the skygear/react-chat-demo is malfunctioning

I followed the instructions provided in the Skygear manual at https://docs.skygear.io/guides/advanced/server/ The skygear-server-darwin-amd64 started successfully. Then, I attempted to run the react-chat-demo project from https://github.com/skygear-de ...

Enhanced form validation using AJAX

Currently, my aim is to implement client-side validation with AJAX in order to check for any empty fields within a basic form. If a field happens to be blank, I intend to alert the user about its invalidity. It is crucial that the form does not get submitt ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

Uh oh! You haven't set a QueryClient yet. Make sure to use QueryClientProvider to set

My first experience with React Query didn't go as planned when I encountered this error at the beginning of my React app: Even though I added QueryClientProvider to the top of my component tree, I kept getting: Error: No QueryClient set, use QueryCli ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

Swap out The div element with the html() method

I'm encountering an issue when trying to swap out a div element with ajax. My goal is to create a start/stop button functionality. The page displays a list of card elements, each with its own button, which are stored in separate html files. work_orde ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Setting up an i18n project in AngularJS

I just embarked on my angularjs journey yesterday with little to no prior knowledge about it. My initial goal is to centralize all the labels for my UI in a file (to facilitate swapping them out for i18n). As far as I know, this can be achieved by importi ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...