consistent-generic-constructors
强制在类型注释或构造函数调用的构造函数名称上指定泛型类型参数.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
构造泛型类时,你可以在左侧(作为类型注释)或右侧(作为构造函数调用的一部分)指定类型参数:
¥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> = 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. 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.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/consistent-generic-constructors": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/consistent-generic-constructors": "error"
}
};
在线运行试试这个规则 ↗
选项
该规则接受以下选项:
type Options = [
/** 首选哪种构造函数调用语法。 */
| 'constructor'
/** 首选哪种构造函数调用语法。 */
| 'type-annotation',
];
const defaultOptions: Options = ['constructor'];
¥Options
-
'constructor'
(默认):不允许仅出现在类型注释中的类型参数。¥
'constructor'
(default): type arguments that only appear on the type annotation are disallowed. -
'type-annotation'
:不允许仅出现在构造函数中的类型参数。¥
'type-annotation'
: type arguments that only appear on the constructor are disallowed.
'constructor'
- ❌ 错误
- ✅ 正确
const map: Map<string, number> = new Map();
const set: Set<string> = new Set();
Open in Playgroundconst 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>();
Open in Playground'type-annotation'
- ❌ 错误
- ✅ 正确
const map = new Map<string, number>();
const set = new Set<string>();
Open in Playgroundconst map: Map<string, number> = new Map();
const set: Set<string> = new Set();
const set = new Set();
const set: Set<string> = new Set<string>();
Open in Playground何时不使用它
¥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.
但是,请记住,不一致的风格可能会损害项目的可读性。我们建议为此规则选择一个最适合你的项目的选项。
¥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.