Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Fix preferConstRule failing with older TypeScript versions #1941

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/language/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,18 @@ export function unwrapParentheses(node: ts.Expression) {
}
return node;
}

/**
* Shim to look up NodeFlags or ModifierFlags depending on the TypeScript
* version, emitting a runtime error if neither can be found.
*/
export function isCombinedFlagSet(node: ts.Node, name: string): boolean {
if (ts.ModifierFlags && name in ts.ModifierFlags) {
return isCombinedModifierFlagSet(node, (<any> ts.ModifierFlags)[name]);
}
if (ts.NodeFlags && name in ts.NodeFlags) {
return isCombinedNodeFlagSet(node, (<any> ts.NodeFlags)[name]);
}

throw new Error(`Cannot find tag "${name}" in either ts.ModifierFlags or ts.NodeFlags`);
}
9 changes: 7 additions & 2 deletions src/rules/preferConstRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@

import * as ts from "typescript";
import * as Lint from "../index";
import {isAssignment, isCombinedModifierFlagSet, isCombinedNodeFlagSet, unwrapParentheses} from "../language/utils";
import {
isAssignment,
isCombinedFlagSet,
isCombinedNodeFlagSet,
unwrapParentheses
} from '../language/utils';

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
Expand Down Expand Up @@ -54,7 +59,7 @@ class PreferConstWalker extends Lint.BlockScopeAwareRuleWalker<{}, ScopeInfo> {
}

private static collectInVariableDeclarationList(node: ts.VariableDeclarationList, scopeInfo: ScopeInfo) {
if (isCombinedNodeFlagSet(node, ts.NodeFlags.Let) && !isCombinedModifierFlagSet(node, ts.ModifierFlags.Export)) {
if (isCombinedNodeFlagSet(node, ts.NodeFlags.Let) && !isCombinedFlagSet(node, 'Export')) {
for (const decl of node.declarations) {
PreferConstWalker.addDeclarationName(decl.name, node, scopeInfo);
}
Expand Down