简体   繁体   中英

Check if anywhere in the code a non-existent property is requested

I have a set of constants, looking like

let codes = {
    OPEN_ACCOUNT: 1000,
    CLOSE_ACCOUNT: 1001,
    DEPOSIT_FUNDS: 3000
    ...
}

Sometimes the keys are renamed, or added, or removed, so the structure of the codes object changes. As the app is quite large, I would be happy to statically analyze the code with some tool like JSLint/TSLint for cases when functions run with the code that is not available anymore:

runServerRequest(codes.DEPOSIT_FUNDS_SPECIAL_CASE, 500)

In the example above DEPOSIT_FUNDS_SPECIAL_CASE is not present in the codes object so it would be great to have a warning from the analyzer. In all possible cases, there shouldn't be cases when a non-existent field is requested.

How do I tackle this task the simplest way?

A way to do this is to set up a Proxy object that will throw if you access a non-existent property:

// define codes above this line.
codes = new Proxy(codes, {
  get: function(target, prop) {
    if (!target.hasOwnProperty(prop)) {
      throw new Error('Attempting to use the deleted code `' + prop + '`.');
    }
    return target[prop]
  }
});

The get method will trap all accesses to code. some_property code. some_property and throw if it isn't defined.
Note that this will not throw if the property has been explicitly set to undefined .

Can I Use?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM