Skip to content

Commit

Permalink
Merge pull request #95 from Microsoft/no-single-element-tuple-type
Browse files Browse the repository at this point in the history
Add 'no-single-element-tuple-type' rule
  • Loading branch information
Andy authored and sandersn committed Nov 29, 2021
1 parent 19f8893 commit d63e292
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/dtslint/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 packages/dtslint/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);
});
}
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]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rulesDirectory": ["../../bin/rules"],
"rules": {
"no-single-element-tuple-type": true
}
}

0 comments on commit d63e292

Please sign in to comment.