mercredi 17 février 2021

How do I obtain a property descriptor inside of a class proxy handler using JavaScript/TypeScript

With a class proxy I would like to interrogate the property descriptor before performing a particular action; do one thing if it's an accessor, do something else if it's a method, and a third thing if it's a property. The problem though is that I don't think I'm looking at the correct owner of the feature:

type Constructor<T> = new (...args: any[]) => T

const handler: ProxyHandler<any> = {
    get(target, propertyKey, receiver) {
        const desc = Object.getOwnPropertyDescriptor(target, propertyKey)
        console.log(desc) // undefined

        return Reflect.get(target, propertyKey, receiver)
    }
}

function Adapted<U extends Constructor<any> = Constructor<any>>(Base: U = Object as any) {
    return class extends Base {
        constructor(...args: any[]) {
            super(...args)

            return new Proxy(this, handler)
        }
    }
}

class Foo extends Adapted() {
    method() { return "foo" }
}

new Foo().method() // "foo"

Do I have to walk the prototype chain until I find the correct owner? Is it something simpler?





Aucun commentaire:

Enregistrer un commentaire