简体   繁体   中英

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

I'd like to be able to use static code analysis tool (standard/eslint) to detect following situation:

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

Both Standard and ESLint will not find any issue here. Is it possible to detect it using good code quality tools?

Just to give example, IDEA/Webstorm is reporting the problem correctly 在此处输入图片说明

so, just wondering, is it possible to detect the same issue using command line tools.

Static type checkers like 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 . Without any modifications to the code to add specific type annotations, both checkers catch the error.

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; }'.

In JavaScript, undefined is a correct value for variables, so you can't detect an assignment of this value. For your problem, I suggest you to define a function like this one :

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

Then you can rewrite your code as followed :

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

Don't forget to catch your throwed exceptions. If you want define your own exception type, it's possible (take a look at https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Error ).

Javascript is not a typed language, so it's not really possible to validate object destructuring before running your code.

For example, when you get a response from an HTTP Request, your code quality tools are not aware of the resulting JSON object.

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