Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 39e41b5

Browse files
octogonzbradzacher
authored andcommitted
fix(eslint-plugin): [typedef] support "for..in", "for..of" (typescript-eslint#787)
1 parent 84916e6 commit 39e41b5

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

packages/eslint-plugin/src/rules/typedef.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,32 @@ export default util.createRule<[Options], MessageIds>({
142142
options[OptionKeys.VariableDeclaration] &&
143143
!node.id.typeAnnotation
144144
) {
145-
report(node, getNodeName(node.id));
145+
// Are we inside a context that does not allow type annotations?
146+
let typeAnnotationRequired = true;
147+
148+
let current: TSESTree.Node | undefined = node.parent;
149+
while (current) {
150+
switch (current.type) {
151+
case AST_NODE_TYPES.VariableDeclaration:
152+
// Keep looking upwards
153+
current = current.parent;
154+
break;
155+
case AST_NODE_TYPES.ForOfStatement:
156+
case AST_NODE_TYPES.ForInStatement:
157+
// Stop traversing and don't report an error
158+
typeAnnotationRequired = false;
159+
current = undefined;
160+
break;
161+
default:
162+
// Stop traversing
163+
current = undefined;
164+
break;
165+
}
166+
}
167+
168+
if (typeAnnotationRequired) {
169+
report(node, getNodeName(node.id));
170+
}
146171
}
147172
},
148173
};

packages/eslint-plugin/tests/rules/typedef.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,31 @@ ruleTester.run('typedef', rule, {
198198
},
199199
],
200200
},
201+
// Contexts where TypeScript doesn't allow annotations
202+
{
203+
code: `for (x of [1, 2, 3]) { }`,
204+
options: [
205+
{
206+
variableDeclaration: true,
207+
},
208+
],
209+
},
210+
{
211+
code: `for (const x in {}) { }`,
212+
options: [
213+
{
214+
variableDeclaration: true,
215+
},
216+
],
217+
},
218+
{
219+
code: `try { } catch (e) { }`,
220+
options: [
221+
{
222+
variableDeclaration: true,
223+
},
224+
],
225+
},
201226
],
202227
invalid: [
203228
// Array destructuring

0 commit comments

Comments
 (0)