forked from typescript-eslint/typescript-eslint
/
prefer-interface.ts
66 lines (61 loc) · 1.9 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
65
66
import { TSESTree } from '@typescript-eslint/typescript-estree';
import { RuleFix } from 'ts-eslint';
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 = { ... })',
tslintRuleName: 'interface-over-type-literal',
category: 'Stylistic Issues',
recommended: 'error',
},
fixable: 'code',
messages: {
interfaceOverType: 'Use an interface instead of a type literal.',
},
schema: [],
deprecated: true,
replacedBy: ['consistent-type-definisions'],
},
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: 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;
},
});
},
};
},
});