forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-empty-interface.ts
104 lines (98 loc) · 2.96 KB
/
no-empty-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
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 * as util from '../util';
import { TSESLint } from '@typescript-eslint/utils';
type Options = [
{
allowSingleExtends?: boolean;
},
];
type MessageIds = 'noEmpty' | 'noEmptyWithSuper';
export default util.createRule<Options, MessageIds>({
name: 'no-empty-interface',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow the declaration of empty interfaces',
recommended: 'error',
},
fixable: 'code',
hasSuggestions: true, // eslint-disable-line eslint-plugin/require-meta-has-suggestions -- https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/issues/272
messages: {
noEmpty: 'An empty interface is equivalent to `{}`.',
noEmptyWithSuper:
'An interface declaring no members is equivalent to its supertype.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowSingleExtends: {
type: 'boolean',
},
},
},
],
},
defaultOptions: [
{
allowSingleExtends: false,
},
],
create(context, [{ allowSingleExtends }]) {
return {
TSInterfaceDeclaration(node): void {
const sourceCode = context.getSourceCode();
const filename = context.getFilename();
if (node.body.body.length !== 0) {
// interface contains members --> Nothing to report
return;
}
const extend = node.extends;
if (!extend || extend.length === 0) {
context.report({
node: node.id,
messageId: 'noEmpty',
});
} else if (extend.length === 1) {
// interface extends exactly 1 interface --> Report depending on rule setting
if (!allowSingleExtends) {
const fix = (fixer: TSESLint.RuleFixer): TSESLint.RuleFix => {
let typeParam = '';
if (node.typeParameters) {
typeParam = sourceCode.getText(node.typeParameters);
}
return fixer.replaceText(
node,
`type ${sourceCode.getText(
node.id,
)}${typeParam} = ${sourceCode.getText(extend[0])}`,
);
};
// Check if interface is within ambient declaration
let useAutoFix = true;
if (util.isDefinitionFile(filename)) {
const scope = context.getScope();
if (scope.type === 'tsModule' && scope.block.declare) {
useAutoFix = false;
}
}
context.report({
node: node.id,
messageId: 'noEmptyWithSuper',
...(useAutoFix
? { fix }
: {
suggest: [
{
messageId: 'noEmptyWithSuper',
fix,
},
],
}),
});
}
}
},
};
},
});