forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-useless-constructor.ts
75 lines (70 loc) · 2.05 KB
/
no-useless-constructor.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
import { TSESTree, AST_NODE_TYPES } from '@typescript-eslint/utils';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
import * as util from '../util';
const baseRule = getESLintCoreRule('no-useless-constructor');
type Options = util.InferOptionsTypeFromRule<typeof baseRule>;
type MessageIds = util.InferMessageIdsTypeFromRule<typeof baseRule>;
/**
* Check if method with accessibility is not useless
*/
function checkAccessibility(node: TSESTree.MethodDefinition): boolean {
switch (node.accessibility) {
case 'protected':
case 'private':
return false;
case 'public':
if (
node.parent &&
node.parent.type === AST_NODE_TYPES.ClassBody &&
node.parent.parent &&
'superClass' in node.parent.parent &&
node.parent.parent.superClass
) {
return false;
}
break;
}
return true;
}
/**
* Check if method is not unless due to typescript parameter properties
*/
function checkParams(node: TSESTree.MethodDefinition): boolean {
return !node.value.params.some(
param => param.type === AST_NODE_TYPES.TSParameterProperty,
);
}
export default util.createRule<Options, MessageIds>({
name: 'no-useless-constructor',
meta: {
type: 'problem',
docs: {
description: 'Disallow unnecessary constructors',
recommended: 'strict',
extendsBaseRule: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
schema: baseRule.meta.schema,
// TODO: this rule has only had messages since v7.0 - remove this when we remove support for v6
messages: baseRule.meta.messages ?? {
noUselessConstructor: 'Useless constructor.',
},
},
defaultOptions: [],
create(context) {
const rules = baseRule.create(context);
return {
MethodDefinition(node): void {
if (
node.value &&
node.value.type === AST_NODE_TYPES.FunctionExpression &&
node.value.body &&
checkAccessibility(node) &&
checkParams(node)
) {
rules.MethodDefinition(node);
}
},
};
},
});