consistent-generic-constructors
Enforce specifying generic type arguments on type annotation or constructor name of a constructor call.
Extending"plugin:@typescript-eslint/stylistic" in anESLint configuration enables this rule.
Some problems reported by this rule are automatically fixable by the--fix ESLint command line option.
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):
// Left-hand side
const map: Map<string,number>=newMap();
// Right-hand side
const map=newMap<string,number>();
This rule ensures that type arguments appear consistently on one side of the declaration.Keeping to one side consistently improve code readability.
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.
- Flat Config
- Legacy Config
exportdefault tseslint.config({
rules:{
"@typescript-eslint/consistent-generic-constructors":"error"
}
});
module.exports={
"rules":{
"@typescript-eslint/consistent-generic-constructors":"error"
}
};
Try this rule in the playground ↗
Options
This rule accepts the following options:
typeOptions=[
/** Which constructor call syntax to prefer. */
|'constructor'
/** Which constructor call syntax to prefer. */
|'type-annotation',
];
const defaultOptions: Options=['constructor'];
'constructor'(default): type arguments thatonly appear on the type annotation are disallowed.'type-annotation': type arguments thatonly appear on the constructor are disallowed.
'constructor'
- ❌ Incorrect
- ✅ Correct
const map: Map<string,number>=newMap();
const set: Set<string>=newSet();
Open in Playgroundconst map=newMap<string,number>();
const map: Map<string,number>=newMyMap();
const set=newSet<string>();
const set=newSet();
const set: Set<string>=newSet<string>();
Open in Playground'type-annotation'
- ❌ Incorrect
- ✅ Correct
const map=newMap<string,number>();
const set=newSet<string>();
Open in Playgroundconst map: Map<string,number>=newMap();
const set: Set<string>=newSet();
const set=newSet();
const set: Set<string>=newSet<string>();
Open in PlaygroundWhen 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.
However, keep in mind that inconsistent style can harm readability in a project.We recommend picking a single option for this rule that works best for your project.