@typescript-eslint/consistent-generic-constructors

Require type arguments on the constructor call or on the type annotation, consistently

fixable

Also called typescript-eslint/consistent-generic-constructors, typescript/consistent-generic-constructors

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:

bunfig.toml
[lint.rules]
"@typescript-eslint/consistent-generic-constructors" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"@typescript-eslint/consistent-generic-constructors" = [
  "error",
  "constructor", # "type-annotation" or "constructor"
]

Examples#

example.ts3 problems
const scores: Map<string, number> = new Map();

class Game {
  players: Set<string> = new Set();
}

function start(seen: Set<string> = new Set()) {}
example.tsNo problems
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:

example.tsNo problems
const scores: ReadonlyMap<string, number> = new Map();

Options#

OptionWhat 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>.
example.tswith "type-annotation"1 problem
const scores = new Map<string, number>();
example.tswith "type-annotation"No problems
const scores: Map<string, number> = new Map();