4 * Copyright 2013 Palantir Technologies, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 Object.defineProperty(exports, "__esModule", { value: true });
19 var tslib_1 = require("tslib");
20 var tsutils = require("tsutils");
21 var ts = require("typescript");
22 var Lint = require("../index");
23 var LEGAL_TYPEOF_RESULTS = new Set([
32 var Rule = /** @class */ (function (_super) {
33 tslib_1.__extends(Rule, _super);
35 return _super !== null && _super.apply(this, arguments) || this;
37 Rule.prototype.apply = function (sourceFile) {
38 return this.applyWithFunction(sourceFile, walk);
40 /* tslint:disable:object-literal-sort-keys */
42 ruleName: "typeof-compare",
43 description: "Makes sure result of `typeof` is compared to correct string values",
44 optionsDescription: "Not configurable.",
46 optionExamples: [true],
47 type: "functionality",
48 typescriptOnly: false,
49 deprecationMessage: !/^2\.1\./.test(ts.version)
50 ? "Starting from TypeScript 2.2 the compiler includes this check which makes this rule redundant."
53 /* tslint:enable:object-literal-sort-keys */
54 Rule.FAILURE_STRING = "'typeof' expression must be compared to one of: " + Array.from(LEGAL_TYPEOF_RESULTS)
55 .map(function (x) { return "\"" + x + "\""; })
58 }(Lint.Rules.AbstractRule));
61 ts.forEachChild(ctx.sourceFile, function cb(node) {
62 if (tsutils.isBinaryExpression(node)) {
63 var operatorToken = node.operatorToken, left = node.left, right = node.right;
64 if (Lint.getEqualsKind(operatorToken) !== undefined &&
65 (isFaultyTypeof(left, right) || isFaultyTypeof(right, left))) {
66 ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
69 ts.forEachChild(node, cb);
72 function isFaultyTypeof(left, right) {
73 return left.kind === ts.SyntaxKind.TypeOfExpression && isFaultyTypeofResult(right);
75 function isFaultyTypeofResult(node) {
77 case ts.SyntaxKind.StringLiteral:
78 return !LEGAL_TYPEOF_RESULTS.has(node.text);
79 case ts.SyntaxKind.Identifier:
80 return node.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword;
81 case ts.SyntaxKind.NullKeyword:
82 case ts.SyntaxKind.NumericLiteral:
83 case ts.SyntaxKind.TrueKeyword:
84 case ts.SyntaxKind.FalseKeyword:
85 case ts.SyntaxKind.ObjectLiteralExpression:
86 case ts.SyntaxKind.ArrayLiteralExpression: