-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): [consistent-generic-constructors] add rule #4924
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
Changes from all commits
8e5d39f
df8de5c
aa7c312
c6434c7
7e29ee3
85b851c
33cb2d3
ba54b9e
46de101
867152a
c40ab67
ff8dfc7
2110540
119393c
371983e
5e49222
63e4cb9
be2f1af
1bdedec
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: do we want to handle namespaced names like There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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! There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
) { | ||
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, '()'); | ||
} | ||
}, | ||
}); | ||
} | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
The logic is that the rule needs the primary option (do we use
constructor
ortype-annotation
?) to be functional at all, and enhancement options only tweak existing behaviors, instead of totally flipping it.See #4924 (comment)