UNPKG

2.86 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var ts = require("typescript");
4var Lint = require("tslint");
5var utils = require("tsutils/typeguard/2.8");
6var Ignore = require("./shared/ignore");
7var check_node_1 = require("./shared/check-node");
8// tslint:disable-next-line:variable-name
9exports.Rule = check_node_1.createCheckNodeRule(Ignore.checkNodeWithIgnore(checkNode), "Unexpected let, use const instead.");
10function checkNode(node, ctx) {
11 var variableStatementFailures = checkVariableStatement(node, ctx);
12 var forStatementsFailures = checkForStatements(node, ctx);
13 return {
14 invalidNodes: variableStatementFailures.concat(forStatementsFailures)
15 };
16}
17function checkVariableStatement(node, ctx) {
18 if (utils.isVariableStatement(node)) {
19 return checkDeclarationList(node.declarationList, ctx);
20 }
21 return [];
22}
23function checkForStatements(node, ctx) {
24 if ((utils.isForStatement(node) ||
25 utils.isForInStatement(node) ||
26 utils.isForOfStatement(node)) &&
27 node.initializer &&
28 utils.isVariableDeclarationList(node.initializer) &&
29 Lint.isNodeFlagSet(node.initializer, ts.NodeFlags.Let)) {
30 return checkDeclarationList(node.initializer, ctx);
31 }
32 return [];
33}
34function checkDeclarationList(declarationList, ctx) {
35 if (Lint.isNodeFlagSet(declarationList, ts.NodeFlags.Let)) {
36 // It is a let declaration, now check each variable that is declared
37 var invalidVariableDeclarationNodes = [];
38 // If the declaration list contains multiple variables, eg. let x = 0, y = 1, mutableZ = 3; then
39 // we should only provide one fix for the list even if two variables are invalid.
40 // NOTE: When we have a mix of allowed and disallowed variables in the same DeclarationList
41 // there is no sure way to know if we should do a fix or not, eg. if ignore-prefix=mutable
42 // and the list is "let x, mutableZ", then "x" is invalid but "mutableZ" is valid, should we change
43 // "let" to "const" or not? For now we change to const if at least one variable is invalid.
44 var addFix = true;
45 for (var _i = 0, _a = declarationList.declarations; _i < _a.length; _i++) {
46 var variableDeclarationNode = _a[_i];
47 if (!Ignore.shouldIgnorePrefix(variableDeclarationNode, ctx.options, ctx.sourceFile)) {
48 invalidVariableDeclarationNodes.push(check_node_1.createInvalidNode(variableDeclarationNode, addFix
49 ? [
50 new Lint.Replacement(declarationList.getStart(ctx.sourceFile), "let".length, "const")
51 ]
52 : []));
53 addFix = false;
54 }
55 }
56 return invalidVariableDeclarationNodes;
57 }
58 return [];
59}
60//# sourceMappingURL=noLetRule.js.map
\No newline at end of file