/
no-misused-new.ts
111 lines (108 loc) · 2.89 KB
/
no-misused-new.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
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
export default util.createRule({
name: 'no-misused-new',
meta: {
type: 'problem',
docs: {
description: 'Enforce valid definition of `new` and `constructor`',
category: 'Best Practices',
recommended: 'error',
},
schema: [],
messages: {
errorMessageInterface: 'Interfaces cannot be constructed, only classes.',
errorMessageClass: 'Class cannon have method named `new`.',
},
},
defaultOptions: [],
create(context) {
/**
* @param {ASTNode} node type to be inspected.
* @returns name of simple type or null
*/
function getTypeReferenceName(
node:
| TSESTree.TSTypeAnnotation
| TSESTree.TypeNode
| TSESTree.EntityName
| undefined,
): string | null {
if (node) {
switch (node.type) {
case AST_NODE_TYPES.TSTypeAnnotation:
return getTypeReferenceName(node.typeAnnotation);
case AST_NODE_TYPES.TSTypeReference:
return getTypeReferenceName(node.typeName);
case AST_NODE_TYPES.Identifier:
return node.name;
default:
break;
}
}
return null;
}
/**
* @param {ASTNode} parent parent node.
* @param {ASTNode} returnType type to be compared
*/
function isMatchingParentType(
parent: undefined | TSESTree.Node,
returnType: TSESTree.TSTypeAnnotation | undefined,
): boolean {
if (
parent &&
'id' in parent &&
parent.id &&
parent.id.type === AST_NODE_TYPES.Identifier
) {
return getTypeReferenceName(returnType) === parent.id.name;
}
return false;
}
return {
'TSInterfaceBody > TSConstructSignatureDeclaration'(
node: TSESTree.TSConstructSignatureDeclaration,
) {
if (
isMatchingParentType(
node.parent!.parent as TSESTree.TSInterfaceDeclaration,
node.returnType,
)
) {
// constructor
context.report({
node,
messageId: 'errorMessageInterface',
});
}
},
"TSMethodSignature[key.name='constructor']"(
node: TSESTree.TSMethodSignature,
) {
context.report({
node,
messageId: 'errorMessageInterface',
});
},
"ClassBody > MethodDefinition[key.name='new']"(
node: TSESTree.MethodDefinition,
) {
if (node.value.type === AST_NODE_TYPES.TSEmptyBodyFunctionExpression) {
if (
node.parent &&
isMatchingParentType(node.parent.parent, node.value.returnType)
) {
context.report({
node,
messageId: 'errorMessageClass',
});
}
}
},
};
},
});