forked from typescript-eslint/typescript-eslint
/
no-empty-interface.ts
116 lines (107 loc) · 3.17 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
105
106
107
108
109
110
111
112
113
114
115
116
import type { TSESLint } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as util from '../util';
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,
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])}`,
);
};
const scope = context.getScope();
const mergedWithClassDeclaration = scope.set
.get(node.id.name)
?.defs?.some(
def => def.node.type === AST_NODE_TYPES.ClassDeclaration,
);
const isInAmbientDeclaration = !!(
util.isDefinitionFile(filename) &&
scope.type === 'tsModule' &&
scope.block.declare
);
const useAutoFix = !(
isInAmbientDeclaration || mergedWithClassDeclaration
);
context.report({
node: node.id,
messageId: 'noEmptyWithSuper',
...(useAutoFix
? { fix }
: !mergedWithClassDeclaration
? {
suggest: [
{
messageId: 'noEmptyWithSuper',
fix,
},
],
}
: null),
});
}
}
},
};
},
});