0

ProxyHandler has following declaration

    /**
     * A trap for getting a property value.
     * @param target The original object which is being proxied.
     * @param p The name or `Symbol` of the property to get.
     * @param receiver The proxy or an object that inherits from the proxy.
     */
    get?(target: T, p: string | symbol, receiver: any): any;

How can i use number as a property key? I guess it is possible to use Proxy for Array, but i got error

const arr = [0, 1, 2, 3, 4, 5]

const proxyHandler: ProxyHandler<typeof arr> = {
        get: (target, key) => {
            console.log(key)
      return target[key]; // Element implicitly has an 'any' type because index expression is not of type 'number'.
    },
}
  
const proxyArray = new Proxy(arr, proxyHandler)

proxyArray[1]

1 Answers1

0

When using Proxy, most of the times, you should use Reflect:

const proxyHandler: ProxyHandler<typeof arr> = {
  get: (target, key, receiver) => {
    console.log(key);
    return Reflect.get(target, key, receiver);
  },
};

See the difference between Reflect.get and obj["foo"] and the Reflect API.

kelsny
  • 23,009
  • 3
  • 19
  • 48