Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Add 'no-const-enum' rule #104

Merged
1 commit merged into from
Jan 23, 2018
Merged
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
16 changes: 16 additions & 0 deletions docs/no-const-enum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# no-const-enum

Avoid using `const enum`s. These can't be used by JavaScript users or by TypeScript users with [`--isolatedModules`](https://www.typescriptlang.org/docs/handbook/compiler-options.html) enabled.

**Bad**:

```ts
const enum Bit { Off, On }
export function f(b: Bit): void;
```

**Good**:

```ts
export function f(b: 0 | 1): void;
```
1 change: 1 addition & 0 deletions dtslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"expect": true,
"export-just-namespace": true,
"no-bad-reference": true,
"no-const-enum": true,
"no-dead-reference": true,
"no-padding": true,
"no-redundant-undefined": true,
Expand Down
32 changes: 32 additions & 0 deletions src/rules/noConstEnumRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import * as Lint from "tslint";
import * as ts from "typescript";

import { failure } from "../util";

export class Rule extends Lint.Rules.AbstractRule {
static metadata: Lint.IRuleMetadata = {
ruleName: "no-const-enum",
description: "Forbid `const enum`",
optionsDescription: "Not configurable.",
options: null,
type: "functionality",
typescriptOnly: true,
};

static FAILURE_STRING = failure(
Rule.metadata.ruleName,
"Use of `const enum`s is forbidden.");

apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}

function walk(ctx: Lint.WalkContext<void>): void {
ctx.sourceFile.forEachChild(function recur(node) {
if (ts.isEnumDeclaration(node) && node.modifiers && node.modifiers.some(m => m.kind === ts.SyntaxKind.ConstKeyword)) {
ctx.addFailureAtNode(node.name, Rule.FAILURE_STRING);
}
node.forEachChild(recur);
});
}
7 changes: 7 additions & 0 deletions test/no-const-enum/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const enum E {
~ [0]
}

enum F {}

[0]: Use of `const enum`s is forbidden. See: https://github.com/Microsoft/dtslint/blob/master/docs/no-const-enum.md
6 changes: 6 additions & 0 deletions test/no-const-enum/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rulesDirectory": ["../../bin/rules"],
"rules": {
"no-const-enum": true
}
}