/
consistent-generic-constructors.ts
99 lines (97 loc) · 3.18 KB
/
consistent-generic-constructors.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
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import { createRule } from '../util';
type MessageIds = 'preferLHS' | 'preferRHS';
type Options = ['lhs' | 'rhs'];
export default createRule<Options, MessageIds>({
name: 'consistent-generic-constructors',
meta: {
type: 'suggestion',
docs: {
description:
'Enforce specifying generic type arguments on LHS or RHS of constructor call',
recommended: false,
},
messages: {
preferLHS:
'The generic type arguments should be specified on the left-hand side of the declaration as a type annotation.',
preferRHS:
'The generic type arguments should be specified on the right-hand side of the declaration as constructor type arguments.',
},
fixable: 'code',
schema: [
{
enum: ['lhs', 'rhs'],
},
],
},
defaultOptions: ['rhs'],
create(context, [mode]) {
return {
VariableDeclarator(node: TSESTree.VariableDeclarator): void {
const sourceCode = context.getSourceCode();
const lhs = node.id.typeAnnotation?.typeAnnotation;
const rhs = node.init;
if (
!rhs ||
rhs.type !== AST_NODE_TYPES.NewExpression ||
rhs.callee.type !== AST_NODE_TYPES.Identifier
) {
return;
}
if (
lhs &&
(lhs.type !== AST_NODE_TYPES.TSTypeReference ||
lhs.typeName.type !== AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name)
) {
return;
}
if (mode === 'lhs' && !lhs && rhs.typeParameters) {
const { typeParameters, callee } = rhs;
const typeAnnotation =
sourceCode.getText(callee) + sourceCode.getText(typeParameters);
context.report({
node,
messageId: 'preferLHS',
fix(fixer) {
return [
fixer.remove(typeParameters),
fixer.insertTextAfter(node.id, ': ' + typeAnnotation),
];
},
});
}
if (mode === 'rhs' && lhs?.typeParameters && !rhs.typeParameters) {
const hasParens = sourceCode.getTokenAfter(rhs.callee)?.value === '(';
const extraComments = new Set(
sourceCode.getCommentsInside(lhs.parent!),
);
sourceCode
.getCommentsInside(lhs.typeParameters)
.forEach(c => extraComments.delete(c));
context.report({
node,
messageId: 'preferRHS',
*fix(fixer) {
yield fixer.remove(lhs.parent!);
for (const comment of extraComments) {
yield fixer.insertTextAfter(
rhs.callee,
// @ts-expect-error: `sourceCode.getText` should accept `TSESTree.Comment`
sourceCode.getText(comment),
);
}
yield fixer.insertTextAfter(
rhs.callee,
sourceCode.getText(lhs.typeParameters),
);
if (!hasParens) {
yield fixer.insertTextAfter(rhs.callee, '()');
}
},
});
}
},
};
},
});