/
no-for-in-array.js
56 lines (51 loc) · 1.52 KB
/
no-for-in-array.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* @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,
messages: {
forInViolation:
'For-in loops over arrays are forbidden. Use for-of or array.forEach instead.'
},
schema: [],
type: 'problem'
},
create(context) {
return {
ForInStatement(node) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = checker.getTypeAtLocation(originalNode.expression);
if (
(typeof type.symbol !== 'undefined' &&
type.symbol.name === 'Array') ||
(type.flags & ts.TypeFlags.StringLike) !== 0
) {
context.report({
node,
messageId: 'forInViolation'
});
}
}
};
}
};