Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [typedef] support "for..in", "for..of" #787

Merged
merged 2 commits into from Aug 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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