@typescript-eslint/consistent-generic-constructors
Require type arguments on the constructor call or on the type annotation, consistently
When you create a generic class, the type arguments can go on the variable (const users: Map<string, User> = new Map()) or on the call (const users = new Map<string, User>()). Both give the same type. This rule picks one place. By default it's the call, which names the class once instead of twice.
The rule checks variables, class fields, and parameters with a default value, except arrow function parameters. It leaves code alone when the type arguments are on both sides, or on neither.
--fix moves the type arguments to the other side.
Configure#
Off by default. To turn it on:
[lint.rules]
"@typescript-eslint/consistent-generic-constructors" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/consistent-generic-constructors" = [
"error",
"constructor", # "type-annotation" or "constructor"
]Examples#
Reported:
const scores: Map<string, number> = new Map();
class Game {
players: Set<string> = new Set();
}
function start(seen: Set<string> = new Set()) {}Not reported:
const scores = new Map<string, number>();
class Game {
players = new Set<string>();
}
function start(seen = new Set<string>()) {}The annotation must name the same class as the call. Here it doesn't, so moving the type arguments would change the variable's type:
const scores: ReadonlyMap<string, number> = new Map();Options#
| Option | What it does |
|---|---|
"constructor" (default) | Type arguments go on the call: new Map<string, number>(). |
"type-annotation" | Type arguments go on the annotation: const scores: Map<string, number>. |
const scores = new Map<string, number>();const scores: Map<string, number> = new Map();