Skip to content
← Back to rules

typescript/ban-ts-comment 严格

🛠️ An auto-fix is available for this rule for some violations.

它的作用

此规则允许你指定在代码库中允许哪些指令注释。

为什么这是不好的?

使用 TypeScript 指令来抑制 TypeScript 编译器错误会降低 TypeScript 整体的有效性。

示例

以下为该规则的错误示例:

ts
if (false) {
  // @ts-ignore: 不可达代码错误
  console.log("hello");
}

配置

此规则允许你指定如何处理不同的 TypeScript 指令注释。

对于每个指令(@ts-expect-error@ts-ignore@ts-nocheck@ts-check),你可以选择以下选项之一:

  • true:完全禁止该指令,阻止其在整个代码库中使用。
  • false:无限制地允许该指令。
  • "allow-with-description":仅当指令后跟一段说明其用途的描述时才允许。该描述必须满足 minimumDescriptionLength 指定的最小长度要求。
  • { "descriptionFormat": "<regex>" }:仅当描述匹配指定的正则表达式模式时才允许该指令。

例如:

json
{
  "ts-expect-error": "allow-with-description",
  "ts-ignore": true,
  "ts-nocheck": { "descriptionFormat": "^: TS\\d+ because .+$" },
  "ts-check": false,
  "minimumDescriptionLength": 3
}

此规则接受一个具有以下属性的配置对象:

minimumDescriptionLength

type: integer

default: 3

使用 allow-with-description 时所需的最小描述长度。

ts-check

如何处理 @ts-check 指令。

ts-expect-error

如何处理 @ts-expect-error 指令。

ts-ignore

如何处理 @ts-ignore 指令。

ts-nocheck

如何处理 @ts-nocheck 指令。

如何使用

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

json
{
  "rules": {
    "typescript/ban-ts-comment": "error"
  }
}
bash
oxlint --deny typescript/ban-ts-comment

参考资料