From 921cdf17e548845311d0591249616ec844503926 Mon Sep 17 00:00:00 2001 From: Joshua Chen Date: Fri, 10 Jun 2022 08:38:44 +0800 Subject: [PATCH] feat(eslint-plugin): [consistent-generic-constructors] add rule (#4924) --- packages/eslint-plugin/README.md | 1 + packages/eslint-plugin/docs/rules/README.md | 1 + .../rules/consistent-generic-constructors.md | 82 +++++++ packages/eslint-plugin/src/configs/all.ts | 1 + packages/eslint-plugin/src/configs/strict.ts | 1 + .../rules/consistent-generic-constructors.ts | 104 +++++++++ packages/eslint-plugin/src/rules/index.ts | 2 + .../consistent-generic-constructors.test.ts | 217 ++++++++++++++++++ packages/utils/src/ts-eslint/SourceCode.ts | 2 +- 9 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 packages/eslint-plugin/docs/rules/consistent-generic-constructors.md create mode 100644 packages/eslint-plugin/src/rules/consistent-generic-constructors.ts create mode 100644 packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts diff --git a/packages/eslint-plugin/README.md b/packages/eslint-plugin/README.md index ff85922117e..60a76994518 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -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:` 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: | | diff --git a/packages/eslint-plugin/docs/rules/README.md b/packages/eslint-plugin/docs/rules/README.md index 41cdb518c1c..805f126f822 100644 --- a/packages/eslint-plugin/docs/rules/README.md +++ b/packages/eslint-plugin/docs/rules/README.md @@ -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:` 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: | | diff --git a/packages/eslint-plugin/docs/rules/consistent-generic-constructors.md b/packages/eslint-plugin/docs/rules/consistent-generic-constructors.md new file mode 100644 index 00000000000..db717dbcbd3 --- /dev/null +++ b/packages/eslint-plugin/docs/rules/consistent-generic-constructors.md @@ -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 = new Map(); + +// Right-hand side +const map = new Map(); +``` + +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` + + + +#### ❌ Incorrect + +```ts +const map: Map = new Map(); +const set: Set = new Set(); +``` + +#### ✅ Correct + +```ts +const map = new Map(); +const map: Map = new MyMap(); +const set = new Set(); +const set = new Set(); +const set: Set = new Set(); +``` + +### `type-annotation` + + + +#### ❌ Incorrect + +```ts +const map = new Map(); +const set = new Set(); +``` + +#### ✅ Correct + +```ts +const map: Map = new Map(); +const set: Set = new Set(); +const set = new Set(); +const set: Set = new Set(); +``` + +## 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. diff --git a/packages/eslint-plugin/src/configs/all.ts b/packages/eslint-plugin/src/configs/all.ts index 5f9562d5bac..8742d36b208 100644 --- a/packages/eslint-plugin/src/configs/all.ts +++ b/packages/eslint-plugin/src/configs/all.ts @@ -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', diff --git a/packages/eslint-plugin/src/configs/strict.ts b/packages/eslint-plugin/src/configs/strict.ts index bb51ebfa4f2..a9c91f7c1ca 100644 --- a/packages/eslint-plugin/src/configs/strict.ts +++ b/packages/eslint-plugin/src/configs/strict.ts @@ -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', diff --git a/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts b/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts new file mode 100644 index 00000000000..0df1412bd7b --- /dev/null +++ b/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({ + 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, '()'); + } + }, + }); + } + } + }, + }; + }, +}); diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index 41afc88199f..29a47ec2384 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -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'; @@ -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, diff --git a/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts b/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts new file mode 100644 index 00000000000..0fe3bcae7fb --- /dev/null +++ b/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts @@ -0,0 +1,217 @@ +import rule from '../../src/rules/consistent-generic-constructors'; +import { RuleTester, noFormat } from '../RuleTester'; + +const ruleTester = new RuleTester({ + parser: '@typescript-eslint/parser', +}); + +ruleTester.run('consistent-generic-constructors', rule, { + valid: [ + // default: constructor + 'const a = new Foo();', + 'const a = new Foo();', + 'const a: Foo = new Foo();', + 'const a: Foo = new Foo();', + 'const a: Bar = new Foo();', + 'const a: Foo = new Foo();', + 'const a: Bar = new Foo();', + 'const a: Bar = new Foo();', + 'const a: Foo = Foo();', + 'const a: Foo = Foo();', + 'const a: Foo = Foo();', + // type-annotation + { + code: 'const a = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Bar = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Bar = new Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = Foo();', + options: ['type-annotation'], + }, + { + code: 'const a: Foo = Foo();', + options: ['type-annotation'], + }, + { + code: 'const a = new (class C {})();', + options: ['type-annotation'], + }, + ], + invalid: [ + { + code: 'const a: Foo = new Foo();', + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: 'const a = new Foo();', + }, + { + code: 'const a: Map = new Map();', + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: 'const a = new Map();', + }, + { + code: noFormat`const a: Map = new Map();`, + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Map();`, + }, + { + code: noFormat`const a: Map< string, number > = new Map();`, + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Map< string, number >();`, + }, + { + code: noFormat`const a: Map = new Map ();`, + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Map ();`, + }, + { + code: noFormat`const a: Foo = new Foo;`, + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Foo();`, + }, + { + code: 'const a: /* comment */ Foo/* another */ = new Foo();', + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Foo/* comment *//* another */();`, + }, + { + code: 'const a: Foo/* comment */ = new Foo /* another */();', + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new Foo/* comment */ /* another */();`, + }, + { + code: noFormat`const a: Foo = new \n Foo \n ();`, + errors: [ + { + messageId: 'preferConstructor', + }, + ], + output: noFormat`const a = new \n Foo \n ();`, + }, + { + code: 'const a = new Foo();', + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: 'const a: Foo = new Foo();', + }, + { + code: 'const a = new Map();', + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: 'const a: Map = new Map();', + }, + { + code: noFormat`const a = new Map ();`, + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: noFormat`const a: Map = new Map ();`, + }, + { + code: noFormat`const a = new Map< string, number >();`, + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: noFormat`const a: Map< string, number > = new Map();`, + }, + { + code: noFormat`const a = new \n Foo \n ();`, + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: noFormat`const a: Foo = new \n Foo \n ();`, + }, + { + code: 'const a = new Foo/* comment */ /* another */();', + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: noFormat`const a: Foo = new Foo/* comment */ /* another */();`, + }, + { + code: 'const a = new Foo();', + options: ['type-annotation'], + errors: [ + { + messageId: 'preferTypeAnnotation', + }, + ], + output: noFormat`const a: Foo = new Foo();`, + }, + ], +}); diff --git a/packages/utils/src/ts-eslint/SourceCode.ts b/packages/utils/src/ts-eslint/SourceCode.ts index 7ecc7ab1b09..17893d25b50 100644 --- a/packages/utils/src/ts-eslint/SourceCode.ts +++ b/packages/utils/src/ts-eslint/SourceCode.ts @@ -276,7 +276,7 @@ declare class SourceCodeBase extends TokenStore { * @returns The text representing the AST node. */ getText( - node?: TSESTree.Node, + node?: TSESTree.Node | TSESTree.Token, beforeCount?: number, afterCount?: number, ): string;