Disallowing setting array properties with TSLint

Viewed 149

I was wondering if there is a TSLint rule with which I can disallow the following code:

var arr = [1, 2];
//the line below should be disallowed
arr.prop1 = "3";
//because arr now has array elements and object properties

I want to disallow this because it prevents arr from being fully serialized with JSON.stringify, because JSON.stringify will serialize arr into [1, 2].

I have looked at the TSLint rules but wasn't able to find a rule for this.

1 Answers

I've implemented a TSLint rule for this, which is available on GitHub and NPM:

It can be used like this:

  • Install it using npm install no-setting-array-properties-rule --save-dev.
  • Add it to your tslint.json, like this:

    {
       "rulesDirectory": [
           "../node_modules/no-setting-array-properties-rule/dist/src"
       ],
       "rules": {
           "no-setting-array-properties": true
       }
    }
    

Edit:

It can be implemented by just setting noImplicitAny: true too, for my project this wasn't an acceptable solution, but that's the easy fix.

Related