VS Code + JavaScript + eslint show error when calling an object with invalid key

74 Views Asked by At

I'm looking for a way for vs code with the combination of eslint to give me an error or a warning when I call an invalid key on an object. In this specific case I've created a global constant object with five keys and when I call something made up like Foo on this object I want there to be an error saying Foo hasn't been defined.

example:

const COLORS = { BLUE: 1, RED: 2, GREEN: 3 }
somefunction(COLORS.foo)  // show warning or error

I Have done a dozen or so searches for answers or extensions looking at ES Lint website , SonarCube Extension and none of these seem to solve this simple problem. Yes I know TS can handle this but our project is in JS.

1

There are 1 best solutions below

1
On

Somewhere, a test exists that looks like this:

assert(whateverFunctionThatAccessOneOfCOLORSProperty() === aValueComputedFrom1or2or3); 

This test fails whenever someone is making use of a value that is not 1, 2 or 3, so there is no need for linting.

What you are trying to achieve is vain because it would only prevent developers from accessing an undefined property of COLORS, but would not prevent them from using a non valid value without accessing COLORS:

import {COLORS} from "./colors";

function computeSomethingFromCOLORS() {
    // don't access COLORS at all
    return 4;
}

Linting would not trigger - because as you can see nobody is accessing COLORS - but the test suite would definitely fail.

Linting is by no mean a replacement for proper testing.

EDIT: This goes true with TypeScript. Typing is not a replacement for testing. It is a convenient way to not having to wait until the compilation is done and the test suite run to detect syntactic issues. No typed language can ever replace a test suite.