如何在TypeScript中使用ProxyHandler和数组?

kadbb459  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(199)

ProxyHandler具有以下声明

/**
     * 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;

我如何使用数字作为一个属性键?我想它是可以使用数组代理,但我得到了错误

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]
km0tfn4u

km0tfn4u1#

当使用代理时,大多数情况下,您应该使用Reflect

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

请参见difference between Reflect.get and obj["foo"]Reflect API

相关问题