Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to construct an object so that it throws an error when its keys are requested?

Imagine I have the following code:

const object = {};
// an error should be thrown
object.property.someMethod();
// an error should be thrown
object.foo;

Is it possible to throw an error when someMethod() is called or if any other non-existing property is called?

I guess that I need to do something with it's prototype, to throw an Error. However, I'm not sure what exactly I should do.

Any help would be appreciated.

like image 802
Le garcon Avatar asked Mar 06 '23 09:03

Le garcon


1 Answers

Yes, using a Proxy with a handler.get() trap:

const object = new Proxy({}, {
  get (target, key) {
    throw new Error(`attempted access of nonexistent key \`${key}\``);
  }
})

object.foo

If you want to modify an existing object with this behavior, you can use Reflect.has() to check for property existence and determine whether to forward the access using Reflect.get() or throw:

const object = new Proxy({
  name: 'Fred',
  age: 42,
  get foo () { return this.bar }
}, {
  get (target, key, receiver) {
    if (Reflect.has(target, key)) {
      return Reflect.get(target, key, receiver)
    } else {
      throw new Error(`attempted access of nonexistent key \`${key}\``)
    }
  }
})

console.log(object.name)
console.log(object.age)
console.log(object.foo)
like image 147
Patrick Roberts Avatar answered Mar 07 '23 23:03

Patrick Roberts