forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
no-for-in-array.ts
41 lines (37 loc) · 1.01 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
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',
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 services = util.getParserServices(context);
const checker = services.program.getTypeChecker();
const type = util.getConstrainedTypeAtLocation(services, node.right);
if (
util.isTypeArrayTypeOrUnionOfArrayTypes(type, checker) ||
(type.flags & ts.TypeFlags.StringLike) !== 0
) {
context.report({
node,
messageId: 'forInViolation',
});
}
},
};
},
});