使用命令行工具检测嵌套的未定义属性 (eslint/standard)

Detecting nested undefined attributes using command line tools (eslint/standard)

我希望能够使用静态代码分析工具 (standard/eslint) 来检测以下情况:

  const obj = {a: {b: 'just a value'}}
  // should be obj.a.b
  const b = obj.a.c
  // so b will be undefined

Standard 和 ESLint 都不会在这里发现任何问题。 是否可以使用良好的代码质量工具来检测它?

举个例子,IDEA/Webstorm 正确地报告了问题

所以,我只是想知道,是否可以使用命令行工具检测到相同的问题。

在JavaScript中,undefined是变量的正确值,因此您无法检测到此值的赋值。 对于你的问题,我建议你定义一个这样的函数:

const assignNested = function(value) {
  if (value === undefined)
    throw new Error("undefined assignment");
  return value;
}

然后你可以重写你的代码如下:

const obj = {a: {b: 'just a value'}};
const b = assignNested(obj.a.b); // b = 'just a value'
const c = assignNested(obj.a.c); // raise exception

不要忘记捕获抛出的异常。如果你想定义你自己的异常类型,这是可能的(看看 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Error)。

Javascript 不是类型化语言,因此在 运行 您的代码之前验证对象解构是不可能的。

例如,当您从 HTTP 请求获得响应时,您的代码质量工具不会识别生成的 JSON 对象。

Flow or TypeScript are designed to catch this class of bugs. Try pasting your example code in either the try Flow editor or the TypeScript playground 这样的静态类型检查器。在不对代码进行任何修改以添加特定类型注释的情况下,两个检查器都捕获了错误。

Flow:

4: const b = obj.a.c
                   ^ property `c`. Property not found in
4: const b = obj.a.c
             ^ object literal

TypeScript:

Property 'c' does not exist on type '{ b: string; }'.