0

like in the title I can't access class method through a proxy object, I get the error

TypeError: sth.getNumber is not a function

But before I see that It was accessed like property because I see "get" log in the terminal

I don't really know why this is happening. Below it's my simplified example of what I want to do. Thanks in advance for help

class mockClass {
  sth?: number
  constructor(n?: number) {
    this.sth = n
  }
  public getNumber(n: number) {
    return n
  }
}

const sth = new Proxy<any>(new mockClass(15), {
  apply: function (target, thisArg, argArr) {
    console.log("apply")
    console.log(target, thisArg, argArr)
    return "a"
  },
  get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return "b"
  },
})

console.log(sth.getNumber(15))
Damian Grzanka
  • 275
  • 2
  • 13

1 Answers1

1

Change:

get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return "b"
  },

To:

get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return () => { return "b"}
  },
Karlan
  • 353
  • 1
  • 2
  • 10
  • I think my answer is a bit primitive but it works. I saw later this discussion with a nice solution. https://stackoverflow.com/questions/25069023/how-do-i-trap-arguments-to-a-target-method-when-using-a-proxy-object – Karlan Aug 26 '20 at 14:39