/
no-this-alias.ts
81 lines (77 loc) · 1.88 KB
/
no-this-alias.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
74
75
76
77
78
79
80
81
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
type Options = [
{
allowDestructuring?: boolean;
allowedNames?: string[];
}
];
type MessageIds = 'thisAssignment' | 'thisDestructure';
export default util.createRule<Options, MessageIds>({
name: 'no-this-alias',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow aliasing `this`',
tslintRuleName: 'no-this-assignment',
category: 'Best Practices',
recommended: false,
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowDestructuring: {
type: 'boolean',
},
allowedNames: {
type: 'array',
items: {
type: 'string',
},
},
},
},
],
messages: {
thisAssignment: "Unexpected aliasing of 'this' to local variable.",
thisDestructure:
"Unexpected aliasing of members of 'this' to local variables.",
},
},
defaultOptions: [
{
allowDestructuring: false,
allowedNames: [],
},
],
create(context, [{ allowDestructuring, allowedNames }]) {
return {
"VariableDeclarator[init.type='ThisExpression']"(
node: TSESTree.VariableDeclarator,
) {
const { id } = node;
if (allowDestructuring && id.type !== AST_NODE_TYPES.Identifier) {
return;
}
const hasAllowedName =
id.type === AST_NODE_TYPES.Identifier
? allowedNames!.includes(id.name)
: false;
if (!hasAllowedName) {
context.report({
node: id,
messageId:
id.type === AST_NODE_TYPES.Identifier
? 'thisAssignment'
: 'thisDestructure',
});
}
},
};
},
});