forked from typescript-eslint/typescript-eslint
/
prefer-interface.ts
64 lines (59 loc) · 1.83 KB
/
prefer-interface.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
import { TSESLint, TSESTree } from '@typescript-eslint/experimental-utils';
import * as util from '../util';
export default util.createRule({
name: 'prefer-interface',
meta: {
type: 'suggestion',
docs: {
description:
'Prefer an interface declaration over a type literal (type T = { ... })',
category: 'Stylistic Issues',
recommended: 'error',
},
fixable: 'code',
messages: {
interfaceOverType: 'Use an interface instead of a type literal.',
},
schema: [],
deprecated: true,
replacedBy: ['consistent-type-definitions'],
},
defaultOptions: [],
create(context) {
const sourceCode = context.getSourceCode();
return {
// VariableDeclaration with kind type has only one VariableDeclarator
"TSTypeAliasDeclaration[typeAnnotation.type='TSTypeLiteral']"(
node: TSESTree.TSTypeAliasDeclaration,
) {
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;
},
});
},
};
},
});