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 9 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 @@ -104,6 +104,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) | Bans `// tslint:<rule-flag>` comments from being used | | :wrench: | |
| [`@typescript-eslint/ban-types`](./docs/rules/ban-types.md) | Bans specific types from being used | :white_check_mark: | :wrench: | |
| [`@typescript-eslint/class-literal-property-style`](./docs/rules/class-literal-property-style.md) | Ensures that literals on classes are exposed in a consistent style | | :wrench: | |
| [`@typescript-eslint/consistent-generic-constructors`](./docs/rules/consistent-generic-constructors.md) | Enforce specifying generic type arguments on LHS or RHS of constructor call | | :wrench: | |
| [`@typescript-eslint/consistent-indexed-object-style`](./docs/rules/consistent-indexed-object-style.md) | Enforce or disallow the use of the record type | | :wrench: | |
| [`@typescript-eslint/consistent-type-assertions`](./docs/rules/consistent-type-assertions.md) | Enforces consistent usage of type assertions | | | |
| [`@typescript-eslint/consistent-type-definitions`](./docs/rules/consistent-type-definitions.md) | Consistent with type definition either `interface` or `type` | | :wrench: | |
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/docs/rules/README.md
Expand Up @@ -28,6 +28,7 @@ slug: /
| [`@typescript-eslint/ban-tslint-comment`](./ban-tslint-comment.md) | Bans `// tslint:<rule-flag>` comments from being used | | :wrench: | |
| [`@typescript-eslint/ban-types`](./ban-types.md) | Bans specific types from being used | :white_check_mark: | :wrench: | |
| [`@typescript-eslint/class-literal-property-style`](./class-literal-property-style.md) | Ensures that literals on classes are exposed in a consistent style | | :wrench: | |
| [`@typescript-eslint/consistent-generic-constructors`](./consistent-generic-constructors.md) | Enforce specifying generic type arguments on LHS or RHS of constructor call | | :wrench: | |
| [`@typescript-eslint/consistent-indexed-object-style`](./consistent-indexed-object-style.md) | Enforce or disallow the use of the record type | | :wrench: | |
| [`@typescript-eslint/consistent-type-assertions`](./consistent-type-assertions.md) | Enforces consistent usage of type assertions | | | |
| [`@typescript-eslint/consistent-type-definitions`](./consistent-type-definitions.md) | Consistent with type definition either `interface` or `type` | | :wrench: | |
Expand Down
@@ -0,0 +1,85 @@
# `consistent-generic-constructors`

Enforce specifying generic type arguments on LHS or RHS of constructor call.

When constructing a generic class, you can specify the type arguments on either the left-hand side or the right-hand side:

```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", "rhs"]
}
}
```

This rule takes a string option:

- If it's set to `rhs` (default), type arguments that **only** appear on the left-hand side are disallowed.
- If it's set to `lhs`, type arguments that **only** appear on the right-hand side 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 two sides don't match.

### `rhs`

<!--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>();
```

### `lhs`

<!--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.

## Attributes

- [ ] ✅ Recommended
- [x] 🔧 Fixable
- [ ] 💭 Requires type information
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
@@ -0,0 +1,99 @@
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import { createRule } from '../util';

type MessageIds = 'preferLHS' | 'preferRHS';
type Options = ['lhs' | 'rhs'];

export default createRule<Options, MessageIds>({
name: 'consistent-generic-constructors',
meta: {
type: 'suggestion',
docs: {
description:
'Enforce specifying generic type arguments on LHS or RHS of constructor call',
recommended: false,
},
messages: {
preferLHS:
'The generic type arguments should be specified on the left-hand side of the constructor call.',
preferRHS:
'The generic type arguments should be specified on the right-hand side of the constructor call.',
},
fixable: 'code',
schema: [
{
enum: ['lhs', 'rhs'],
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

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

I'm under the impression we generally try to use objects for the schemas. They're a bit more future-proof and enforce using a property key to explain what the object is for. Only a few rules still have an enum schema.

type: "object" with additionalProperties: false is preferred.

(are there docs on this anywhere in this project or ESLint core? we should write some somewhere if not...)

Copy link
Member Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

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

String option is preferred when a rule enforces two kinds of styles, and the rule needs to know which side you are on to be functional at all. Object option is used when you are making refinements to the given style. To give a few examples:

I noticed that we tend to use an object containing a prefer property, but IMO that deviates from ESLint core's API design😅 Sometimes ESLint core would have both string and object, like func-name-matching. When you really look into it, you would understand the differing semantics between string and object.

},
],
},
defaultOptions: ['rhs'],
create(context, [mode]) {
return {
VariableDeclarator(node: TSESTree.VariableDeclarator): void {
Copy link
Member

Choose a reason for hiding this comment

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

Yeah the types for these queries can be tricky. More support of us using fancy template literal magicks to parse them (#4065).

Going off the "complex types are from complex code" philosophy: how about splitting this into two queries? VariableDeclarator[init.callee.type='Identifier'][init.type='NewExpression'] could run just the right-hand-side logic.

Search NodeWithModifiers and TypeParameterWithConstraint for examples of places where we've had to manually adjust node types in the past.

Copy link
Member Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

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

I'm not particularly good at AST selectors, so I always felt a bit cornered when I have to use them...

Also, we simultaneously need lhs and rhs, and there are a few cases (especially lhs.typeName.name !== rhs.callee.name) where we kind of depend on both for refinement, so I've kept it like this.

Copy link
Member Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

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

I tried, it was ugly refined types like

type TargetVariableDeclarator = TSESTree.VariableDeclarator & {
  init: TSESTree.VariableDeclarator["init"] & {
    type: AST_NODE_TYPES.NewExpression;
    callee: Extract<TSESTree.VariableDeclarator["init"], { callee: unknown }>["callee"] & {
      type: AST_NODE_TYPES.Identifier;
    }
  };
};

Combined with ugly selectors😇 I suggest we don't do it?

const sourceCode = context.getSourceCode();
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 === 'lhs' && !lhs && rhs.typeParameters) {
const { typeParameters, callee } = rhs;
const typeAnnotation =
sourceCode.getText(callee) + sourceCode.getText(typeParameters);
context.report({
node,
messageId: 'preferLHS',
fix(fixer) {
return [
fixer.remove(typeParameters),
fixer.insertTextAfter(node.id, ': ' + typeAnnotation),
];
},
});
}
if (mode === 'rhs' && 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: 'preferRHS',
*fix(fixer) {
yield fixer.remove(lhs.parent!);
for (const comment of extraComments) {
yield fixer.insertTextAfter(
rhs.callee,
// @ts-expect-error: `sourceCode.getText` should accept `TSESTree.Comment`
sourceCode.getText(comment),
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
);
}
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