Utilizing mapped types in a proxy solution

As I was going through the TS Handbook, I stumbled upon mapped types where there's a code snippet demonstrating how to wrap an object property into a proxy.

type Proxy<T> = {
    get(): T;
    set(value: T): void;
}
type Proxify<T> = {
    [P in keyof T]: Proxy<T[P]>;
}
function proxify<T>(o: T): Proxify<T> {
   // ... wrap proxies ...
}
let proxyProps = proxify(props);

While trying to enhance the proxify function with my own implementation, I encountered the following issue:

function proxify<T>(t: T): Proxify<T> {
    let result = <Proxify<T>>{};
    for (const k in t) {
      result[k] = {    //(*) from that moment I lose strong typing  
        get: () => t[k],
        set: (value) => t[k] = value
      }
    }
    return result;
  }

The problem arises within the loop as I'm unable to enforce type control and everything defaults to any. How can I address this issue while ensuring the correctness of my implementation?

Answer №1

The approach appears to be solid. Although there is a slight compromise on safety when creating the object, it's not completely lost. You may find yourself pleasantly surprised by the amount of code reduction achieved.

function proxyfy<T>(t: T): Proxyfy<T> {
    let result = <Proxyfy<T>>{};
    for (const k in t) { // k is of type Extract<keyof T, string> ensuring validity as a key of T
        result[k] = { 
            get: () => t[k],
            set: (value) => t[k] = value
        }
    }
    return result;
}

Answer №2

My approach to implementation is outlined below. Despite my efforts, I was unable to find a way to enforce type safety in the get and set methods. It would have been more graceful if there existed a method to define properties such as get():PropType , set(value:PropType)

function createProxy<T>(obj: T): ProxyObject<T> {
        const proxy: ProxyObject<T> = <ProxyObject<T>>{};
        Object.keys(obj).map((key) => {
            proxy[key] = {
                get() {
                    return obj[key];
                },
                set(value) {
                    obj[key] = value;
                }
            };

        });
        return proxy;
    }

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

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Refreshing the private route redirects the user to the login page

Currently, I am working on setting up a private route within my React app. I have integrated Redux and Redux-Toolkit (RTK) Query for handling state management and data fetching. The issue I am facing is that whenever I reload the private page, it redirects ...

I'm trying to figure out how to access the array field of an object in TypeScript. It seems like the type 'unknown' is required to have a '[Symbol.iterator]()' method that returns an iterator

I'm currently tackling an issue with my helper function that updates a form field based on the fieldname. For example, if it's the name field, then form.name will be updated. If it's user[0].name, then the name at index 0 of form.users will ...

Necessary Typescript class property when executing code

Is there a way to determine if a class property is required in Typescript at runtime? export class A { public readonly ab?: number; public readonly ac?: number; public readonly ad: number; public readonly ae: number; } Can emitDecoratorMetadata o ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

Updating from Angular version 12.0.4 to 12.1.0 results in a runtime error. As a temporary solution, we are reverting back to version 12.0

There is a related issue discussed here: Angular: TypeError: Cannot read property 'firstCreatePass' of null However, the problem in that case pertains to different Angular versions and the solution provided did not resolve my issue. The recurring ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

What is the best way to retrieve data (using GET) following React state changes?

Whenever a user clicks on one of the orderBy buttons (such as name/email/date), a new rendered result should be fetched from the server by sending a new get request. The same applies to page pagination. Simply setting this.setState({ [thestate]: [newState ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

Typescript encounters issues when assigning declaration as TRUE

Currently, I'm working on a project in Angular 2 and attempting to create TypeScript definitions for it so that it can be exported as a library. I have various services set up that make HTTP requests to components, all structured similarly to the cod ...

Set up Admin SDK using appropriate credentials for the given environment

As someone new to Node.js, Firebase Cloud Functions, and TypeScript, my objective is to create a cloud function that acts as an HTTP endpoint for clients to authenticate with Firebase. The desired outcome is for the cloud function to provide a custom acces ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

When it comes to TypeScript, there is a limitation in assigning a value to an object key with type narrowing through the

I created a function called `hasOwnProperty` with type narrowing: function hasOwnProperty< Obj extends Record<string, any>, Prop extends PropertyKey, >( obj: Obj, prop: Prop, ): obj is Obj & Record<Prop, any> { return Object ...