/
no-for-in-array.ts
43 lines (40 loc) · 1.15 KB
/
no-for-in-array.ts
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
import * as ts from 'typescript';
import * as util from '../util';
export default util.createRule({
name: 'no-for-in-array',
meta: {
docs: {
description: 'Disallow iterating over an array with a for-in loop',
category: 'Best Practices',
recommended: 'error',
requiresTypeChecking: true,
},
messages: {
forInViolation:
'For-in loops over arrays are forbidden. Use for-of or array.forEach instead.',
},
schema: [],
type: 'problem',
},
defaultOptions: [],
create(context) {
return {
ForInStatement(node): void {
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',
});
}
},
};
},
});