From 56034736fb3ce6b4d573996a78d408966f67649d Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Tue, 27 Aug 2019 12:56:31 -0400 Subject: [PATCH] fix(eslint-plugin): [typedef] don't flag destructuring when variables is disabled (#819) --- packages/eslint-plugin/src/rules/typedef.ts | 51 +++++++++---------- .../eslint-plugin/tests/rules/typedef.test.ts | 18 +++++++ 2 files changed, 43 insertions(+), 26 deletions(-) diff --git a/packages/eslint-plugin/src/rules/typedef.ts b/packages/eslint-plugin/src/rules/typedef.ts index 182568e5748..3d9d76f3872 100644 --- a/packages/eslint-plugin/src/rules/typedef.ts +++ b/packages/eslint-plugin/src/rules/typedef.ts @@ -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)); }, }; }, diff --git a/packages/eslint-plugin/tests/rules/typedef.test.ts b/packages/eslint-plugin/tests/rules/typedef.test.ts index b1a7b08bcf0..d5ea514f59e 100644 --- a/packages/eslint-plugin/tests/rules/typedef.test.ts +++ b/packages/eslint-plugin/tests/rules/typedef.test.ts @@ -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]) { }`,