Skip to content

Commit

Permalink
fix(eslint-plugin): [typedef] support "for..in", "for..of" (#787)
Browse files Browse the repository at this point in the history
  • Loading branch information
octogonz authored and bradzacher committed Aug 2, 2019
1 parent 84916e6 commit 39e41b5
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
27 changes: 26 additions & 1 deletion packages/eslint-plugin/src/rules/typedef.ts
Expand Up @@ -142,7 +142,32 @@ export default util.createRule<[Options], MessageIds>({
options[OptionKeys.VariableDeclaration] &&
!node.id.typeAnnotation
) {
report(node, getNodeName(node.id));
// Are we inside a context that does not allow type annotations?
let typeAnnotationRequired = true;

let current: TSESTree.Node | undefined = node.parent;
while (current) {
switch (current.type) {
case AST_NODE_TYPES.VariableDeclaration:
// Keep looking upwards
current = current.parent;
break;
case AST_NODE_TYPES.ForOfStatement:
case AST_NODE_TYPES.ForInStatement:
// Stop traversing and don't report an error
typeAnnotationRequired = false;
current = undefined;
break;
default:
// Stop traversing
current = undefined;
break;
}
}

if (typeAnnotationRequired) {
report(node, getNodeName(node.id));
}
}
},
};
Expand Down
25 changes: 25 additions & 0 deletions packages/eslint-plugin/tests/rules/typedef.test.ts
Expand Up @@ -198,6 +198,31 @@ ruleTester.run('typedef', rule, {
},
],
},
// Contexts where TypeScript doesn't allow annotations
{
code: `for (x of [1, 2, 3]) { }`,
options: [
{
variableDeclaration: true,
},
],
},
{
code: `for (const x in {}) { }`,
options: [
{
variableDeclaration: true,
},
],
},
{
code: `try { } catch (e) { }`,
options: [
{
variableDeclaration: true,
},
],
},
],
invalid: [
// Array destructuring
Expand Down

0 comments on commit 39e41b5

Please sign in to comment.