/
consistent-type-definitions.ts
102 lines (94 loc) · 2.99 KB
/
consistent-type-definitions.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
import { TSESLint, TSESTree } from '@typescript-eslint/experimental-utils';
import * as util from '../util';
export default util.createRule({
name: 'consistent-type-definitions',
meta: {
type: 'suggestion',
docs: {
description:
'Consistent with type definition either `interface` or `type`',
category: 'Stylistic Issues',
recommended: 'error',
},
messages: {
interfaceOverType: 'Use an `interface` instead of a `type`',
typeOverInterface: 'Use a `type` instead of an `interface`',
},
schema: [
{
enum: ['interface', 'type'],
},
],
fixable: 'code',
},
defaultOptions: ['interface'],
create(context, [option]) {
const sourceCode = context.getSourceCode();
return {
"TSTypeAliasDeclaration[typeAnnotation.type='TSTypeLiteral']"(
node: TSESTree.TSTypeAliasDeclaration,
) {
if (option === 'interface') {
context.report({
node: node.id,
messageId: 'interfaceOverType',
fix(fixer) {
const typeNode = node.typeParameters || node.id;
const fixes: TSESLint.RuleFix[] = [];
const firstToken = sourceCode.getFirstToken(node);
if (firstToken) {
fixes.push(fixer.replaceText(firstToken, 'interface'));
fixes.push(
fixer.replaceTextRange(
[typeNode.range[1], node.typeAnnotation.range[0]],
' ',
),
);
}
const afterToken = sourceCode.getTokenAfter(node.typeAnnotation);
if (
afterToken &&
afterToken.type === 'Punctuator' &&
afterToken.value === ';'
) {
fixes.push(fixer.remove(afterToken));
}
return fixes;
},
});
}
},
TSInterfaceDeclaration(node) {
if (option === 'type') {
context.report({
node: node.id,
messageId: 'typeOverInterface',
fix(fixer) {
const typeNode = node.typeParameters || node.id;
const fixes: TSESLint.RuleFix[] = [];
const firstToken = sourceCode.getFirstToken(node);
if (firstToken) {
fixes.push(fixer.replaceText(firstToken, 'type'));
fixes.push(
fixer.replaceTextRange(
[typeNode.range[1], node.body.range[0]],
' = ',
),
);
}
if (node.extends) {
node.extends.forEach(heritage => {
const typeIdentifier = sourceCode.getText(heritage);
fixes.push(
fixer.insertTextAfter(node.body, ` & ${typeIdentifier}`),
);
});
}
return fixes;
},
});
}
},
};
},
});