forked from typescript-eslint/typescript-eslint
/
consistent-indexed-object-style.ts
163 lines (147 loc) · 4.45 KB
/
consistent-indexed-object-style.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils';
import { createRule } from '../util';
type MessageIds = 'preferRecord' | 'preferIndexSignature';
type Options = ['record' | 'index-signature'];
export default createRule<Options, MessageIds>({
name: 'consistent-indexed-object-style',
meta: {
type: 'suggestion',
docs: {
description: 'Require or disallow the `Record` type',
recommended: 'strict',
},
messages: {
preferRecord: 'A record is preferred over an index signature.',
preferIndexSignature: 'An index signature is preferred over a record.',
},
fixable: 'code',
schema: [
{
enum: ['record', 'index-signature'],
},
],
},
defaultOptions: ['record'],
create(context, [mode]) {
const sourceCode = context.getSourceCode();
function checkMembers(
members: TSESTree.TypeElement[],
node: TSESTree.TSTypeLiteral | TSESTree.TSInterfaceDeclaration,
parentId: TSESTree.Identifier | undefined,
prefix: string,
postfix: string,
safeFix = true,
): void {
if (members.length !== 1) {
return;
}
const [member] = members;
if (member.type !== AST_NODE_TYPES.TSIndexSignature) {
return;
}
const [parameter] = member.parameters;
if (!parameter) {
return;
}
if (parameter.type !== AST_NODE_TYPES.Identifier) {
return;
}
const keyType = parameter.typeAnnotation;
if (!keyType) {
return;
}
const valueType = member.typeAnnotation;
if (!valueType) {
return;
}
if (parentId) {
const scope = context.getScope();
const superVar = scope.set.get(parentId.name);
if (superVar) {
const isCircular = superVar.references.some(
item =>
item.isTypeReference &&
node.range[0] <= item.identifier.range[0] &&
node.range[1] >= item.identifier.range[1],
);
if (isCircular) {
return;
}
}
}
context.report({
node,
messageId: 'preferRecord',
fix: safeFix
? (fixer): TSESLint.RuleFix => {
const key = sourceCode.getText(keyType.typeAnnotation);
const value = sourceCode.getText(valueType.typeAnnotation);
const record = member.readonly
? `Readonly<Record<${key}, ${value}>>`
: `Record<${key}, ${value}>`;
return fixer.replaceText(node, `${prefix}${record}${postfix}`);
}
: null,
});
}
return {
...(mode === 'index-signature' && {
TSTypeReference(node): void {
const typeName = node.typeName;
if (typeName.type !== AST_NODE_TYPES.Identifier) {
return;
}
if (typeName.name !== 'Record') {
return;
}
const params = node.typeParameters?.params;
if (params?.length !== 2) {
return;
}
context.report({
node,
messageId: 'preferIndexSignature',
fix(fixer) {
const key = sourceCode.getText(params[0]);
const type = sourceCode.getText(params[1]);
return fixer.replaceText(node, `{ [key: ${key}]: ${type} }`);
},
});
},
}),
...(mode === 'record' && {
TSTypeLiteral(node): void {
const parent = findParentDeclaration(node);
checkMembers(node.members, node, parent?.id, '', '');
},
TSInterfaceDeclaration(node): void {
let genericTypes = '';
if ((node.typeParameters?.params ?? []).length > 0) {
genericTypes = `<${node.typeParameters?.params
.map(p => sourceCode.getText(p))
.join(', ')}>`;
}
checkMembers(
node.body.body,
node,
node.id,
`type ${node.id.name}${genericTypes} = `,
';',
!node.extends?.length,
);
},
}),
};
},
});
function findParentDeclaration(
node: TSESTree.Node,
): TSESTree.TSTypeAliasDeclaration | undefined {
if (node.parent && node.parent.type !== AST_NODE_TYPES.TSTypeAnnotation) {
if (node.parent.type === AST_NODE_TYPES.TSTypeAliasDeclaration) {
return node.parent;
}
return findParentDeclaration(node.parent);
}
return undefined;
}