[英]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. 有时,键会被重命名,添加或删除,因此
codes
对象的结构会发生变化。 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: 由于应用程序很大,因此我很乐意使用诸如JSLint / TSLint之类的工具来静态分析代码,以防函数使用不再可用的代码运行:
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. 在上面的示例中,代码对象中不存在
DEPOSIT_FUNDS_SPECIAL_CASE
,因此从分析器收到警告将非常好。 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: 一种方法是设置一个
Proxy
对象 ,如果您访问不存在的属性,该对象将抛出:
// 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
get
方法将捕获对code. some_property
所有访问code. some_property
code. some_property
and throw if it isn't defined. code. some_property
,如果code. some_property
抛出。
Note that this will not throw if the property has been explicitly set to undefined
. 请注意,如果属性已显式设置为
undefined
, 则不会抛出此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.