Skip to content

Commit

Permalink
feat(eslint-plugin): [consistent-generic-constructors] add rule (#4924)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena committed Jun 10, 2022
1 parent 1f25daf commit 921cdf1
Show file tree
Hide file tree
Showing 9 changed files with 410 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -102,6 +102,7 @@ Pro Tip: For larger codebases you may want to consider splitting our linting int
| [`@typescript-eslint/ban-tslint-comment`](./docs/rules/ban-tslint-comment.md) | Disallow `// tslint:<rule-flag>` comments | :lock: | :wrench: | |
| [`@typescript-eslint/ban-types`](./docs/rules/ban-types.md) | Disallow certain types | :white_check_mark: | :wrench: | |
| [`@typescript-eslint/class-literal-property-style`](./docs/rules/class-literal-property-style.md) | Enforce that literals on classes are exposed in a consistent style | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-generic-constructors`](./docs/rules/consistent-generic-constructors.md) | Enforce specifying generic type arguments on type annotation or constructor name of a constructor call | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-indexed-object-style`](./docs/rules/consistent-indexed-object-style.md) | Require or disallow the `Record` type | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-type-assertions`](./docs/rules/consistent-type-assertions.md) | Enforce consistent usage of type assertions | :lock: | | |
| [`@typescript-eslint/consistent-type-definitions`](./docs/rules/consistent-type-definitions.md) | Enforce type definitions to consistently use either `interface` or `type` | :lock: | :wrench: | |
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/docs/rules/README.md
Expand Up @@ -24,6 +24,7 @@ See [Configs](/docs/linting/configs) for how to enable recommended rules using c
| [`@typescript-eslint/ban-tslint-comment`](./ban-tslint-comment.md) | Disallow `// tslint:<rule-flag>` comments | :lock: | :wrench: | |
| [`@typescript-eslint/ban-types`](./ban-types.md) | Disallow certain types | :white_check_mark: | :wrench: | |
| [`@typescript-eslint/class-literal-property-style`](./class-literal-property-style.md) | Enforce that literals on classes are exposed in a consistent style | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-generic-constructors`](./consistent-generic-constructors.md) | Enforce specifying generic type arguments on type annotation or constructor name of a constructor call | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-indexed-object-style`](./consistent-indexed-object-style.md) | Require or disallow the `Record` type | :lock: | :wrench: | |
| [`@typescript-eslint/consistent-type-assertions`](./consistent-type-assertions.md) | Enforce consistent usage of type assertions | :lock: | | |
| [`@typescript-eslint/consistent-type-definitions`](./consistent-type-definitions.md) | Enforce type definitions to consistently use either `interface` or `type` | :lock: | :wrench: | |
Expand Down
@@ -0,0 +1,82 @@
# `consistent-generic-constructors`

Enforces specifying generic type arguments on type annotation or constructor name of a constructor call.

When constructing a generic class, you can specify the type arguments on either the left-hand side (as a type annotation) or the right-hand side (as part of the constructor call):

```ts
// Left-hand side
const map: Map<string, number> = new Map();

// Right-hand side
const map = new Map<string, number>();
```

This rule ensures that type arguments appear consistently on one side of the declaration.

## Options

```jsonc
{
"rules": {
"@typescript-eslint/consistent-generic-constructors": [
"error",
"constructor"
]
}
}
```

This rule takes a string option:

- If it's set to `constructor` (default), type arguments that **only** appear on the type annotation are disallowed.
- If it's set to `type-annotation`, type arguments that **only** appear on the constructor are disallowed.

## Rule Details

The rule never reports when there are type parameters on both sides, or neither sides of the declaration. It also doesn't report if the names of the type annotation and the constructor don't match.

### `constructor`

<!--tabs-->

#### ❌ Incorrect

```ts
const map: Map<string, number> = new Map();
const set: Set<string> = new Set();
```

#### ✅ Correct

```ts
const map = new Map<string, number>();
const map: Map<string, number> = new MyMap();
const set = new Set<string>();
const set = new Set();
const set: Set<string> = new Set<string>();
```

### `type-annotation`

<!--tabs-->

#### ❌ Incorrect

```ts
const map = new Map<string, number>();
const set = new Set<string>();
```

#### ✅ Correct

```ts
const map: Map<string, number> = new Map();
const set: Set<string> = new Set();
const set = new Set();
const set: Set<string> = new Set<string>();
```

## When Not To Use It

You can turn this rule off if you don't want to enforce one kind of generic constructor style over the other.
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -18,6 +18,7 @@ export = {
'@typescript-eslint/comma-dangle': 'error',
'comma-spacing': 'off',
'@typescript-eslint/comma-spacing': 'error',
'@typescript-eslint/consistent-generic-constructors': 'error',
'@typescript-eslint/consistent-indexed-object-style': 'error',
'@typescript-eslint/consistent-type-assertions': 'error',
'@typescript-eslint/consistent-type-definitions': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/strict.ts
Expand Up @@ -9,6 +9,7 @@ export = {
'@typescript-eslint/ban-tslint-comment': 'warn',
'@typescript-eslint/class-literal-property-style': 'warn',
'@typescript-eslint/consistent-indexed-object-style': 'warn',
'@typescript-eslint/consistent-generic-constructors': 'warn',
'@typescript-eslint/consistent-type-assertions': 'warn',
'@typescript-eslint/consistent-type-definitions': 'warn',
'dot-notation': 'off',
Expand Down
104 changes: 104 additions & 0 deletions packages/eslint-plugin/src/rules/consistent-generic-constructors.ts
@@ -0,0 +1,104 @@
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { createRule } from '../util';

type MessageIds = 'preferTypeAnnotation' | 'preferConstructor';
type Options = ['type-annotation' | 'constructor'];

export default createRule<Options, MessageIds>({
name: 'consistent-generic-constructors',
meta: {
type: 'suggestion',
docs: {
description:
'Enforce specifying generic type arguments on type annotation or constructor name of a constructor call',
recommended: 'strict',
},
messages: {
preferTypeAnnotation:
'The generic type arguments should be specified as part of the type annotation.',
preferConstructor:
'The generic type arguments should be specified as part of the constructor type arguments.',
},
fixable: 'code',
schema: [
{
enum: ['type-annotation', 'constructor'],
},
],
},
defaultOptions: ['constructor'],
create(context, [mode]) {
const sourceCode = context.getSourceCode();
return {
VariableDeclarator(node): void {
const lhs = node.id.typeAnnotation?.typeAnnotation;
const rhs = node.init;
if (
!rhs ||
rhs.type !== AST_NODE_TYPES.NewExpression ||
rhs.callee.type !== AST_NODE_TYPES.Identifier
) {
return;
}
if (
lhs &&
(lhs.type !== AST_NODE_TYPES.TSTypeReference ||
lhs.typeName.type !== AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name)
) {
return;
}
if (mode === 'type-annotation') {
if (!lhs && rhs.typeParameters) {
const { typeParameters, callee } = rhs;
const typeAnnotation =
sourceCode.getText(callee) + sourceCode.getText(typeParameters);
context.report({
node,
messageId: 'preferTypeAnnotation',
fix(fixer) {
return [
fixer.remove(typeParameters),
fixer.insertTextAfter(node.id, ': ' + typeAnnotation),
];
},
});
}
return;
}
if (mode === 'constructor') {
if (lhs?.typeParameters && !rhs.typeParameters) {
const hasParens =
sourceCode.getTokenAfter(rhs.callee)?.value === '(';
const extraComments = new Set(
sourceCode.getCommentsInside(lhs.parent!),
);
sourceCode
.getCommentsInside(lhs.typeParameters)
.forEach(c => extraComments.delete(c));
context.report({
node,
messageId: 'preferConstructor',
*fix(fixer) {
yield fixer.remove(lhs.parent!);
for (const comment of extraComments) {
yield fixer.insertTextAfter(
rhs.callee,
sourceCode.getText(comment),
);
}
yield fixer.insertTextAfter(
rhs.callee,
sourceCode.getText(lhs.typeParameters),
);
if (!hasParens) {
yield fixer.insertTextAfter(rhs.callee, '()');
}
},
});
}
}
},
};
},
});
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -8,6 +8,7 @@ import braceStyle from './brace-style';
import classLiteralPropertyStyle from './class-literal-property-style';
import commaDangle from './comma-dangle';
import commaSpacing from './comma-spacing';
import consistentGenericConstructors from './consistent-generic-constructors';
import consistentIndexedObjectStyle from './consistent-indexed-object-style';
import consistentTypeAssertions from './consistent-type-assertions';
import consistentTypeDefinitions from './consistent-type-definitions';
Expand Down Expand Up @@ -136,6 +137,7 @@ export default {
'class-literal-property-style': classLiteralPropertyStyle,
'comma-dangle': commaDangle,
'comma-spacing': commaSpacing,
'consistent-generic-constructors': consistentGenericConstructors,
'consistent-indexed-object-style': consistentIndexedObjectStyle,
'consistent-type-assertions': consistentTypeAssertions,
'consistent-type-definitions': consistentTypeDefinitions,
Expand Down

0 comments on commit 921cdf1

Please sign in to comment.