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

Add 'no-single-element-tuple-type' rule #95

Merged
1 commit merged into from
Dec 12, 2017
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
15 changes: 15 additions & 0 deletions docs/no-single-element-tuple-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# no-single-element-tuple-type

Some users mistakenly write `[T]` when then intend to write an array type `T[]`.

**Bad**:

```ts
export const x: [T];
```

**Good**:

```ts
export const x: T[];
```
31 changes: 31 additions & 0 deletions src/rules/noSingleElementTupleTypeRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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-single-element-tuple-type",
description: "Forbids `[T]`, which should be `T[]`.",
optionsDescription: "Not configurable.",
options: null,
type: "functionality",
typescriptOnly: true,
};

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

function walk(ctx: Lint.WalkContext<void>): void {
const { sourceFile } = ctx;
sourceFile.forEachChild(function cb(node) {
if (ts.isTupleTypeNode(node) && node.elementTypes.length === 1) {
ctx.addFailureAtNode(node, failure(
Rule.metadata.ruleName,
"Type [T] is a single-element tuple type. You probably meant T[]."));
}
node.forEachChild(cb);
});
}
5 changes: 5 additions & 0 deletions test/no-single-element-tuple-type/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const x: [string];
~~~~~~~~
const y: [string, number];

[0]: [Type [T] is a single-element tuple type. You probably meant T[]. See: https://github.com/Microsoft/dtslint/blob/master/docs/no-padding.md]
6 changes: 6 additions & 0 deletions test/no-single-element-tuple-type/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rulesDirectory": ["../../bin/rules"],
"rules": {
"no-single-element-tuple-type": true
}
}