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

Commit ccce6f9

Browse files
author
Andy
authored
Merge pull request #95 from Microsoft/no-single-element-tuple-type
Add 'no-single-element-tuple-type' rule
2 parents 4967147 + b9402ed commit ccce6f9

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed

docs/no-single-element-tuple-type.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# no-single-element-tuple-type
2+
3+
Some users mistakenly write `[T]` when then intend to write an array type `T[]`.
4+
5+
**Bad**:
6+
7+
```ts
8+
export const x: [T];
9+
```
10+
11+
**Good**:
12+
13+
```ts
14+
export const x: T[];
15+
```
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import * as Lint from "tslint";
2+
import * as ts from "typescript";
3+
4+
import { failure } from "../util";
5+
6+
export class Rule extends Lint.Rules.AbstractRule {
7+
static metadata: Lint.IRuleMetadata = {
8+
ruleName: "no-single-element-tuple-type",
9+
description: "Forbids `[T]`, which should be `T[]`.",
10+
optionsDescription: "Not configurable.",
11+
options: null,
12+
type: "functionality",
13+
typescriptOnly: true,
14+
};
15+
16+
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
17+
return this.applyWithFunction(sourceFile, walk);
18+
}
19+
}
20+
21+
function walk(ctx: Lint.WalkContext<void>): void {
22+
const { sourceFile } = ctx;
23+
sourceFile.forEachChild(function cb(node) {
24+
if (ts.isTupleTypeNode(node) && node.elementTypes.length === 1) {
25+
ctx.addFailureAtNode(node, failure(
26+
Rule.metadata.ruleName,
27+
"Type [T] is a single-element tuple type. You probably meant T[]."));
28+
}
29+
node.forEachChild(cb);
30+
});
31+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const x: [string];
2+
~~~~~~~~
3+
const y: [string, number];
4+
5+
[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]
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"rulesDirectory": ["../../bin/rules"],
3+
"rules": {
4+
"no-single-element-tuple-type": true
5+
}
6+
}

0 commit comments

Comments
 (0)