Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(eslint-plugin): [consistent-generic-constructors] add rule #4924

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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.
Comment on lines +32 to +33
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a nitpick / personal preference

personally I have found that an object for the options is better than a string.
The issue with starting at a string is that if later you want to add options... well you're stuck and you have to support the string and the object form until you remember to breaking-change remove it (if you remember... which we often don't 😓).

Using an object is also nice as it is self-documenting in a way.

i.e.

['error', 'constructor']
// vs
['error', {prefer: 'constructor'}]

Copy link
Member Author

@Josh-Cena Josh-Cena May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, we should have both—i.e., if we have enhancement options in the future, those should be put third. ESLint follows this convention, e.g.

"arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": true }]

The logic is that the rule needs the primary option (do we use constructor or type-annotation?) to be functional at all, and enhancement options only tweak existing behaviors, instead of totally flipping it.

See #4924 (comment)


## 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)
Comment on lines +46 to +47
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: do we want to handle namespaced names like
const foo: immutable.Set<string> = new immutable.Set();

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah we should... is there a utility function to match potentially nested qualified names?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't - I don't think it's something we do all that much!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's leave it off for now - we can add it in later.
It's not super common to be doing this.

) {
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