Skip to content

Commit

Permalink
fix(eslint-plugin): [typedef] don't flag destructuring when variables…
Browse files Browse the repository at this point in the history
… is disabled (#819)
  • Loading branch information
Josh Goldberg authored and bradzacher committed Aug 27, 2019
1 parent 16136f3 commit 5603473
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 26 deletions.
51 changes: 25 additions & 26 deletions packages/eslint-plugin/src/rules/typedef.ts
Expand Up @@ -141,36 +141,35 @@ export default util.createRule<[Options], MessageIds>({
},
VariableDeclarator(node): void {
if (
options[OptionKeys.VariableDeclaration] &&
!node.id.typeAnnotation
!options[OptionKeys.VariableDeclaration] ||
node.id.typeAnnotation ||
(node.id.type === AST_NODE_TYPES.ArrayPattern &&
!options[OptionKeys.ArrayDestructuring]) ||
(node.id.type === AST_NODE_TYPES.ObjectPattern &&
!options[OptionKeys.ObjectDestructuring])
) {
// 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;
}
}
return;
}

if (typeAnnotationRequired) {
report(node, getNodeName(node.id));
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
return;
default:
// Stop traversing
current = undefined;
break;
}
}

report(node, getNodeName(node.id));
},
};
},
Expand Down
18 changes: 18 additions & 0 deletions packages/eslint-plugin/tests/rules/typedef.test.ts
Expand Up @@ -198,6 +198,24 @@ ruleTester.run('typedef', rule, {
},
],
},
{
code: `const [a, b] = [1, 2];`,
options: [
{
objectDestructuring: false,
variableDeclaration: true,
},
],
},
{
code: `const { a, b } = { a: '', b: '' };`,
options: [
{
objectDestructuring: false,
variableDeclaration: true,
},
],
},
// Contexts where TypeScript doesn't allow annotations
{
code: `for (x of [1, 2, 3]) { }`,
Expand Down

0 comments on commit 5603473

Please sign in to comment.