Skip to content
← Back to rules

typescript/consistent-generic-constructors Style

🛠️ 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"

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

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "typescript/consistent-generic-constructors": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "typescript/consistent-generic-constructors": "error",
  },
});
bash
oxlint --deny typescript/consistent-generic-constructors

版本

此规则在 v0.14.0 中添加。

参考资料