-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
no-parameter-properties.ts
114 lines (106 loc) · 2.66 KB
/
no-parameter-properties.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
type Modifier =
| 'readonly'
| 'private'
| 'protected'
| 'public'
| 'private readonly'
| 'protected readonly'
| 'public readonly';
type Options = [
{
allows: Modifier[];
}
];
type MessageIds = 'noParamProp';
export default util.createRule<Options, MessageIds>({
name: 'no-parameter-properties',
meta: {
type: 'problem',
docs: {
description:
'Disallow the use of parameter properties in class constructors.',
tslintRuleName: 'no-parameter-properties',
category: 'Stylistic Issues',
recommended: 'error',
},
messages: {
noParamProp:
'Property {{parameter}} cannot be declared in the constructor.',
},
schema: [
{
type: 'object',
properties: {
allows: {
type: 'array',
items: {
enum: [
'readonly',
'private',
'protected',
'public',
'private readonly',
'protected readonly',
'public readonly',
],
},
minItems: 1,
},
},
additionalProperties: false,
},
],
},
defaultOptions: [
{
allows: [],
},
],
create(context, [{ allows }]) {
/**
* Gets the modifiers of `node`.
* @param node the node to be inspected.
*/
function getModifiers(node: TSESTree.TSParameterProperty): Modifier {
const modifiers: Modifier[] = [];
if (node.accessibility) {
modifiers.push(node.accessibility);
}
if (node.readonly) {
modifiers.push('readonly');
}
return modifiers.filter(Boolean).join(' ') as Modifier;
}
return {
TSParameterProperty(node) {
const modifiers = getModifiers(node);
if (allows.indexOf(modifiers) === -1) {
// HAS to be an identifier or assignment or TSC will throw
if (
node.parameter.type !== AST_NODE_TYPES.Identifier &&
node.parameter.type !== AST_NODE_TYPES.AssignmentPattern
) {
return;
}
const name =
node.parameter.type === AST_NODE_TYPES.Identifier
? node.parameter.name
: // has to be an Identifier or TSC will throw an error
(node.parameter.left as TSESTree.Identifier).name;
context.report({
node,
messageId: 'noParamProp',
data: {
parameter: name,
},
});
}
},
};
},
});