Skip to content
This repository was archived by the owner on Jan 19, 2019. It is now read-only.

[FEAT] [no-for-in-array] Add rule #250

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ This guarantees 100% compatibility between the plugin and the parser.
| [`typescript/no-empty-interface`](./docs/rules/no-empty-interface.md) | Disallow the declaration of empty interfaces (`no-empty-interface` from TSLint) | | |
| [`typescript/no-explicit-any`](./docs/rules/no-explicit-any.md) | Disallow usage of the `any` type (`no-any` from TSLint) | | |
| [`typescript/no-extraneous-class`](./docs/rules/no-extraneous-class.md) | Forbids the use of classes as namespaces (`no-unnecessary-class` from TSLint) | | |
| [`typescript/no-for-in-array`](./docs/rules/no-for-in-array.md) | Disallow iterating over an array with a for-in loop (`no-for-in-array` from TSLint) | | |
| [`typescript/no-inferrable-types`](./docs/rules/no-inferrable-types.md) | Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean. (`no-inferrable-types` from TSLint) | | :wrench: |
| [`typescript/no-misused-new`](./docs/rules/no-misused-new.md) | Enforce valid definition of `new` and `constructor`. (`no-misused-new` from TSLint) | | |
| [`typescript/no-namespace`](./docs/rules/no-namespace.md) | Disallow the use of custom TypeScript modules and namespaces (`no-namespace` from TSLint) | | |
Expand Down
4 changes: 2 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Roadmap
# Roadmap

## TSLint rules

Expand Down Expand Up @@ -59,7 +59,7 @@
| [`no-empty`] | 🌟 | [`no-empty`](https://eslint.org/docs/rules/no-empty) |
| [`no-eval`] | 🌟 | [`no-eval`](https://eslint.org/docs/rules/no-eval) |
| [`no-floating-promises`] | 🛑 | N/A ([relevant plugin](https://github.com/xjamundx/eslint-plugin-promise)) |
| [`no-for-in-array`] | 🛑 | N/A |
| [`no-for-in-array`] | | [`typescript/no-for-in-array`] |
| [`no-implicit-dependencies`] | 🔌 | [`import/no-extraneous-dependencies`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md) |
| [`no-inferred-empty-object-type`] | 🛑 | N/A |
| [`no-invalid-template-strings`] | 🌟 | [`no-template-curly-in-string`](https://eslint.org/docs/rules/no-template-curly-in-string) |
Expand Down
36 changes: 36 additions & 0 deletions docs/rules/no-for-in-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Disallow iterating over an array with a for-in loop (no-for-in-array)

This rule prohibits iterating over an array with a for-in loop.

## Rule Details

Rationale from TSLint:

> A for-in loop (for (var k in o)) iterates over the properties of an Object.
> While it is legal to use for-in loops with array types, it is not common. for-in will iterate over the indices of the array as strings, omitting any “holes” in the array.
> More common is to use for-of, which iterates over the values of an array. If you want to iterate over the indices, alternatives include:
> array.forEach((value, index) => { … }); for (const [index, value] of array.entries()) { … } for (let i = 0; i < array.length; i++) { … }

Examples of **incorrect** code for this rule:

```js
for (const x in [3, 4, 5]) {
console.log(x);
}
```

Examples of **correct** code for this rule:

```js
for (const x in { a: 3, b: 4, c: 5 }) {
console.log(x);
}
```

## When Not To Use It

If you want to iterate through a loop using the indices in an array as strings, you can turn off this rule.

## Related to

- TSLint: ['no-for-in-array'](https://palantir.github.io/tslint/rules/no-for-in-array/)
68 changes: 68 additions & 0 deletions lib/rules/no-for-in-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* @fileoverview Disallow iterating over an array with a for-in loop
* @author Benjamin Lichtman
*/
"use strict";
const ts = require("typescript");
const util = require("../util");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/**
* @type {import("eslint").Rule.RuleModule}
*/
module.exports = {
meta: {
docs: {
description: "Disallow iterating over an array with a for-in loop",
category: "Functionality",
recommended: false,
extraDescription: [util.tslintRule("no-for-in-array")],
url: util.metaDocsUrl("no-for-in-array"),
},
fixable: null,
schema: [],
type: "problem",
},

create(context) {
return {
ForInStatement(node) {
if (
!context.parserServices ||
!context.parserServices.program
) {
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does context.parserServices.program exist when create is first called, as implied by #230? If so, could you...

  • ...return an empty object instead of one with ForInStatement?
  • ...move the checker = context...getTypechecker() call to outside this returned function?

The two would be nice as precedent for other rules that would have multiple methods using the type checker.

Apologies if this is well known; I'm very new to ESLint. 😊

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should use https://github.com/bradzacher/eslint-plugin-typescript/blob/master/lib/util.js#L114

you need access to context and context is parameter of function create(context)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TSLint will warn for each rule enabled that requires type information when it's not provided. Should there be some standard way for these to warn in a similar manner? Would that be a separate issue from this PR?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


/**
* @type {ts.TypeChecker}
*/
const checker = context.parserServices.program.getTypeChecker();
const originalNode = context.parserServices.esTreeNodeToTSNodeMap.get(
node
);

if (!originalNode) {
return;
}

const type = checker.getTypeAtLocation(originalNode.expression);

if (
(typeof type.symbol !== "undefined" &&
type.symbol.name === "Array") ||
(type.flags & ts.TypeFlags.StringLike) !== 0
) {
context.report({
node,
message:
"For-in loops over arrays are forbidden. Use for-of or array.forEach instead.",
});
}
},
};
},
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"typescript": "~3.1.1"
},
"peerDependencies": {
"eslint": ">=4.13.1 < 6"
"eslint": ">=4.13.1 < 6",
"typescript": "*"
},
"lint-staged": {
"*.js": [
Expand Down
Empty file added tests/lib/fixtures/empty.ts
Empty file.
8 changes: 8 additions & 0 deletions tests/lib/fixtures/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
84 changes: 84 additions & 0 deletions tests/lib/rules/no-for-in-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @fileoverview Disallow iterating over an array with a for-in loop
* @author Benjamin Lichtman
*/
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const rule = require("../../../lib/rules/no-for-in-array"),
RuleTester = require("eslint").RuleTester,
path = require("path");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

// RuleTester.it = function(text, method) {
// return method.call({ break: true });
// };

const rootDir = path.join(process.cwd(), "tests/lib/fixtures");
const filename = path.join(rootDir, "empty.ts");
const parserOptions = {
ecmaVersion: 2015,
tsconfigRootDir: rootDir,
project: "./tsconfig.json",
};
const ruleTester = new RuleTester({
parserOptions,
parser: "typescript-eslint-parser",
});
const message =
"For-in loops over arrays are forbidden. Use for-of or array.forEach instead.";

ruleTester.run("no-for-in-array", rule, {
valid: [
{
code: `
for (const x of [3, 4, 5]) {
console.log(x);
}`,
filename,
},
{
filename,
code: `
for (const x in { a: 1, b: 2, c: 3 }) {
console.log(x);
}`,
},
],

invalid: [
{
filename,
code: `
for (const x in [3, 4, 5]) {
console.log(x);
}`,
errors: [
{
message,
type: "ForInStatement",
},
],
},
{
filename,
code: `
const z = [3, 4, 5];
for (const x in z) {
console.log(x);
}`,
errors: [
{
message,
type: "ForInStatement",
},
],
},
],
});