Differentiate between JavaScript Set and immutable Set

Viewed 706

I recently ran into an issue where I ended up using the JavaScript Set object without instantiating using the new operator. I use immutable in my project and was expecting to use the Set construct from there, but I forgot to import it.

As expected, the code crashed as the code expected me to write let set = new Set() instead of just let set = Set().

Are there any es-lint rules available that can help in catching such kind of issues?

1 Answers

You can add an custom no-restricted-globals rule:

"no-restricted-globals": [
    "error",
    {
        "name": "Set",
        "message": "Use window.Set or add an eslint-ignore if native Set is what you want"
    },
    {
        "name": "Map",
        "message": "Use window.Map or add an eslint-ignore if native Map is what you want"
    }
],

Our project used ImmutableJS inconsequently in the beginning so we ended up with a lot of these issues. One of the worst was when someone migrated code from one file to another and both JavaScript Set and Immutable Set were used. Suddendly untouched code started to fail because an import { Set } from 'immutable'; shadowed the native class.

Two things helped us detect these problems:

  • Whenever we intentionally wanted to use native JavaScript types, we prefixed them with the technically useless, but visually obvious window scope: new window.Set()
  • Since it is a react project, we used prop-types and react-immutable-proptypes on all the components. Never use PropTypes.object though, that rule is almost always true!
Related