/
consistent-generic-constructors.ts
104 lines (102 loc) · 3.3 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
100
101
102
103
104
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { createRule } from '../util';
type MessageIds = 'preferTypeAnnotation' | 'preferConstructor';
type Options = ['type-annotation' | 'constructor'];
export default createRule<Options, MessageIds>({
name: 'consistent-generic-constructors',
meta: {
type: 'suggestion',
docs: {
description:
'Enforce specifying generic type arguments on type annotation or constructor name of a constructor call',
recommended: 'strict',
},
messages: {
preferTypeAnnotation:
'The generic type arguments should be specified as part of the type annotation.',
preferConstructor:
'The generic type arguments should be specified as part of the constructor type arguments.',
},
fixable: 'code',
schema: [
{
enum: ['type-annotation', 'constructor'],
},
],
},
defaultOptions: ['constructor'],
create(context, [mode]) {
const sourceCode = context.getSourceCode();
return {
VariableDeclarator(node): void {
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 === 'type-annotation') {
if (!lhs && rhs.typeParameters) {
const { typeParameters, callee } = rhs;
const typeAnnotation =
sourceCode.getText(callee) + sourceCode.getText(typeParameters);
context.report({
node,
messageId: 'preferTypeAnnotation',
fix(fixer) {
return [
fixer.remove(typeParameters),
fixer.insertTextAfter(node.id, ': ' + typeAnnotation),
];
},
});
}
return;
}
if (mode === 'constructor') {
if (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: 'preferConstructor',
*fix(fixer) {
yield fixer.remove(lhs.parent!);
for (const comment of extraComments) {
yield fixer.insertTextAfter(
rhs.callee,
sourceCode.getText(comment),
);
}
yield fixer.insertTextAfter(
rhs.callee,
sourceCode.getText(lhs.typeParameters),
);
if (!hasParens) {
yield fixer.insertTextAfter(rhs.callee, '()');
}
},
});
}
}
},
};
},
});