From 35f601f913da52e87c7d1d8e4a5cf81e3bb0757f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anton=20Str=C3=B6mkvist?= Date: Wed, 2 Nov 2016 14:21:50 +0100 Subject: [PATCH] feat: Add excludeVariableTypes option to require-variable-type Enable ignoring all var, let, or const independently --- .README/rules/require-variable-type.md | 24 ++++++++++++ src/rules/requireVariableType.js | 7 ++++ tests/rules/assertions/requireVariableType.js | 37 +++++++++++++++++++ 3 files changed, 68 insertions(+) diff --git a/.README/rules/require-variable-type.md b/.README/rules/require-variable-type.md index 92745f2a..2d66eb19 100644 --- a/.README/rules/require-variable-type.md +++ b/.README/rules/require-variable-type.md @@ -23,4 +23,28 @@ The default pattern is `a^`, which doesn't match anything, i.e., all parameters ``` +You can choose specific variable types (`var`, `let`, and `const`) to ignore using `excludeVariableTypes`. + +This excludes `var` and `let` declarations from needing type annotations, but forces `const` declarations to have it. +By default, all declarations are checked. + +```js +{ + "rules": { + "flowtype/require-variable-type": [ + 2, + { + "excludeVariableTypes": { + "var": true, + "let": true, + "const": false, + } + } + ] + } +} +``` + + + diff --git a/src/rules/requireVariableType.js b/src/rules/requireVariableType.js index 7d2ddd3d..73264508 100644 --- a/src/rules/requireVariableType.js +++ b/src/rules/requireVariableType.js @@ -12,9 +12,16 @@ export default (context) => { } const excludeVariableMatch = new RegExp(_.get(context, 'options[0].excludeVariableMatch', 'a^')); + const excludeVariableTypes = _.get(context, 'options[0].excludeVariableTypes', {}); return { VariableDeclaration: (variableDeclaration) => { + const variableType = _.get(variableDeclaration, 'kind'); + + if (_.get(excludeVariableTypes, variableType)) { + return; + } + _.forEach(variableDeclaration.declarations, (variableDeclarator) => { const identifierNode = _.get(variableDeclarator, 'id'); const identifierName = _.get(identifierNode, 'name'); diff --git a/tests/rules/assertions/requireVariableType.js b/tests/rules/assertions/requireVariableType.js index 3b08b66f..0c208833 100644 --- a/tests/rules/assertions/requireVariableType.js +++ b/tests/rules/assertions/requireVariableType.js @@ -28,6 +28,22 @@ export default { excludeVariableMatch: '^_' } ] + }, + { + code: 'var foo = "bar", bar = 1; const oob : string = "oob"; let hey = "yah"', + errors: [ + { + message: 'Missing "hey" variable type annotation.' + } + ], + options: [ + { + excludeVariableTypes: { + let: false, + var: true + } + } + ] } ], valid: [ @@ -44,6 +60,27 @@ export default { excludeVariableMatch: '^_' } ] + }, + { + code: 'var foo = "bar", bar = 1', + options: [ + { + excludeVariableTypes: { + var: true + } + } + ] + }, + { + code: 'var foo = "bar", bar = 1; const oob : string = "oob"; let hey = "yah"', + options: [ + { + excludeVariableTypes: { + let: true, + var: true + } + } + ] } ] };