What is the best way to detect object changes in typescript?

Having an object and the desire to listen for changes in order to execute certain actions, my initial approach in ES6 would have been:

let members = {};
let targetProxy = new Proxy(members, {
    set: function (members, key, value) {
        console.log(key + " set to " + value);
        members[key] = value;
        return true;
    }
});

After converting to TypeScript:

const members = {};
let targetProxy: any = new Proxy(members, {
    set: function (members: any, key: string, value: string) {
        console.log(`${key} set to ${value}`);
        members[key] = value;
        return true;
    }
});

However, encountering an error message from the linter:

[ts] Cannot find name 'Proxy'.

The terminal displays the following output:

Despite conducting extensive research, I am unable to troubleshoot the issue.

In an attempt to resolve it, I modified my module parameter to ES6 instead of commonjs, but no changes were observed. Full output can be seen below:

Furthermore, here is a snippet from my package.json configuration:

{
  "compilerOptions": {
    "module": "ES6",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": [
    "src/**/*"
  ]
}

Answer №1

For your project to function correctly, ensure that the TypeScript compiler options are set to target ES2015 or a newer version (documentation). The command-line option should be --target "ES2015" (or "ES2016", etc., or "ESNext" for the latest proposed features).


Additional information: The set method captures property value assignments in the conventional manner but does not do so when using Object.defineProperty:

const members = {};
let targetProxy = new Proxy(members, {
    set: function(members, key, value) {
        console.log(`${key} set to ${value}`);
        members[key] = value;
        return true;
    }
});
console.log("---- Notice no set trap fired:");
console.log(`targetProxy.foo: ${targetProxy.foo}`);
Object.defineProperty(targetProxy, "foo", {
  value: 1,
  writable: true,
  configurable: true,
  enumerable: true
});
console.log(`targetProxy.foo: ${targetProxy.foo}`);
Object.defineProperty(targetProxy, "foo", {
  value: 2,
  writable: true,
  configurable: true,
  enumerable: true
});
console.log(`targetProxy.foo: ${targetProxy.foo}`);
console.log("---- But it's fired for simple assignment:");
console.log(`targetProxy.bar: ${targetProxy.bar}`);
targetProxy.bar = 1;
console.log(`targetProxy.bar: ${targetProxy.bar}`);
targetProxy.bar = 2;
console.log(`targetProxy.bar: ${targetProxy.bar}`);
.as-console-wrapper {
  max-height: 100% !important;
}

In addition, you need a defineProperty trap for this functionality. (Note that both set and defineProperty will be activated when setting a data property, provided that set allows the operation to proceed.)

(Please note that other changes like property deletions, modifications to the prototype, etc., are not captured by these traps.)


Another point to consider: The key parameter in the set trap is of type string | Symbol, not just string.

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

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...

Is it possible to access your app directly from the browser without requiring any user prompts?

After successfully setting up my app for both android and ios with the necessary app link and universal link, I am now focusing on redirecting users from a specific website to my app. The mobile aspect is all set, but I need to work on the browser/server s ...

The file '.manage.py' cannot be accessed due to error code [Errno 2], as the file or directory does not exist

Currently, I'm following a tutorial on a YouTube video. Here is the link: https://www.youtube.com/watch?v=JD-age0BPVo&t=793s While using VSC on my Mac, I encountered the following error: Sourav@Souravs-MBP Settle_Guide % python .\manage.py m ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, ' ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Combine Sonarqube coverage with Istanbuljs/NYC for enhanced code analysis

In my typescript project, we utilize a Jenkins pipeline to run all functional tests in parallel after building the main container. Towards the end of the pipeline, we conduct a code coverage check and then transfer the results to sonarqube. Below is an ex ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this? Below is my code: .ts file this.form = this.formBuilder.group({ ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Unable to find solutions for all parameters needed by a CustomComponent within Angular

Whenever I attempt to compile the project for production, an error pops up: There is a problem resolving all parameters for EmployeeComponent in C:/.../src/app/employee/employee.component.ts: (?, ?, ?). Oddly enough, when I run the application, every ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...