/
no-unsafe-member-access.ts
73 lines (64 loc) · 2.09 KB
/
no-unsafe-member-access.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { TSESTree } from '@typescript-eslint/experimental-utils';
import * as util from '../util';
const enum State {
Unsafe = 1,
Safe = 2,
}
export default util.createRule({
name: 'no-unsafe-member-access',
meta: {
type: 'problem',
docs: {
description: 'Disallows member access on any typed variables',
category: 'Possible Errors',
recommended: false,
requiresTypeChecking: true,
},
messages: {
unsafeMemberExpression:
'Unsafe member access {{property}} on an any value',
},
schema: [],
},
defaultOptions: [],
create(context) {
const { program, esTreeNodeToTSNodeMap } = util.getParserServices(context);
const checker = program.getTypeChecker();
const sourceCode = context.getSourceCode();
const stateCache = new Map<TSESTree.Node, State>();
function checkMemberExpression(
node: TSESTree.MemberExpression | TSESTree.OptionalMemberExpression,
): State {
const cachedState = stateCache.get(node);
if (cachedState) {
return cachedState;
}
if (util.isMemberOrOptionalMemberExpression(node.object)) {
const objectState = checkMemberExpression(node.object);
if (objectState === State.Unsafe) {
// if the object is unsafe, we know this will be unsafe as well
// we don't need to report, as we have already reported on the inner member expr
stateCache.set(node, objectState);
return objectState;
}
}
const tsNode = esTreeNodeToTSNodeMap.get(node.object);
const state = util.isAnyType(tsNode, checker) ? State.Unsafe : State.Safe;
stateCache.set(node, state);
if (state === State.Unsafe) {
const propertyName = sourceCode.getText(node.property);
context.report({
node,
messageId: 'unsafeMemberExpression',
data: {
property: node.computed ? `[${propertyName}]` : `.${propertyName}`,
},
});
}
return state;
}
return {
'MemberExpression, OptionalMemberExpression': checkMemberExpression,
};
},
});