Skip to content
← Back to rules

typescript/consistent-generic-constructors 风格

An auto-fix is available for this rule.

它的作用

在构造泛型类时,你可以在左侧(作为类型注解)或右侧(作为构造函数调用的一部分)指定类型参数。

此规则强制要求泛型构造函数的使用方式保持一致。

为什么这是不好的?

泛型构造函数使用方式不一致会使代码更难阅读和维护。

示例

以下为 错误 的代码示例:

ts
const a: Foo<string> = new Foo();
const a = new Foo<string>(); // 倾向于使用类型注解

以下为 正确 的代码示例:

ts
const a = new Foo<string>();
const a: Foo<string> = new Foo(); // 倾向于使用类型注解

配置

此规则接受一个配置对象,包含以下属性:

option

type: "constructor" | "type-annotation"

default: "constructor"

指定泛型类型应在哪里指定。

可能的值:

  • "constructor"(默认):禁止仅出现在类型注解中的类型参数。
  • "type-annotation":禁止仅出现在构造函数中的类型参数。

"constructor"

禁止仅出现在类型注解中的类型参数。

"type-annotation"

禁止仅出现在构造函数中的类型参数。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/consistent-generic-constructors": "error"
  }
}
bash
oxlint --deny typescript/consistent-generic-constructors

参考资料