Question

Given an example code:

var yyy = { abc : 1 },
    xxx = yyy.abcc + 1;

It won't throw any error but there is a typo where yyy.abcc should be yyy.abc, so xxx is now equal to "NaN" because of the typo error.

I use jslint, jshint to check for problems in codes but it won't tell you if abcc is a valid property or not.

Is there any tools like jslint, or jshint out there that can check this?

Was it helpful?

Solution

Handling these types of common typos and bugs is indeed a massive hole in the Javascript ecosystem, which I wished more people cared about. The fact that this question was asked eight years ago, and still hasn't received a good answer is a huge concern.

I've looked at a bunch of Javascript tools, and the only one I found that sort of works for your case is the Typescript compiler tsc.

Unfortunately, because of the dynamic nature of Javascript maps, it doesn't technically handle your case in the exact way you wrote it, since maps don't have strict attributes that can be enforced, even by a compiler. However, it does work if you instead use a proper Javascript class, which you really should be doing anyways for the other benefits classes provide.

For example, if I rewrite your code as:

class MyClass {
    constructor() {
        this.abc = 1;
    }
}

var yyy = new MyClass();
var xxx = yyy.abcc + 1;

and put it in the file test.js, then create a Typescript config file tsconfig.json file containing (mostly just the default output from tsc --init):

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "test.js"
  ]
}

and then run:

tsc --build tsconfig.json

it correctly outputs the error:

test.js:11:15 - error TS2551: Property 'abcc' does not exist on type 'MyClass'. Did you mean 'abc'?

11 var xxx = yyy.abcc + 1;
                 ~~~~

  test.js:6:9
    6         this.abc = 1;
              ~~~~~~~~~~~~
    'abc' is declared here.


Found 1 error.

Even better, it suggests a useful solution, which is a rarity among compilers.

To install tsc and the type definitions it depends on, you can run:

sudo npm install typescript -g
npm install @types/node --save-dev

OTHER TIPS

Don't complicate things :) The first answer was a good one, every object in javascript has a prototype which can be check by means of "if (undefined != yyy.abc)" this will tell you if "abc" exists withing the var yyy proving yyy is not undefined itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top