DEV Community

Matthew Gong
Matthew Gong

Posted on

TypeScript: Use Mapped Type to implement a Proxy

There is a piece of code in TypeScript's document about Mapped Types which illustrates how to use mapped type to implement a proxy. It clearly defines what the type of a proxy for a value is, i.e. Proxy<T> and what the type of a proxified object is, i.e. Proxify<T>. However, the implementation of the proxify function is left empty. In order to strengthen my understanding of the mapped type, I decided to implement it.

type Proxy<T> = {
    get(): T;
    set(value: T): void;
};

type Proxify<T> = {
    [K in keyof T]: Proxy<T[K]>;
};

function proxify<T extends object>(o: T): Proxify<T> {
    const result = {} as Proxify<T>;
    for (let key in o) {
        let rawValue = o[key];
        result[key] = {
            get: () => rawValue,
            set: (value) => {
                rawValue = value;
            },
        };
    }
    return result;
}

let props = { rooms: 4 };
let proxifiedProps = proxify(props);
proxifiedProps.rooms.set(5);
console.log(proxifiedProps.rooms.get()); // output 5
Enter fullscreen mode Exit fullscreen mode

As you see, it's not difficult however it can help learners like me to get a better understanding of the concept.

Top comments (0)