ban-ts-comment
禁止
@ts-<指令>注释或要求在指令后添加描述。
在 "plugin:@typescript-eslint/recommended" 的 ESLint 配置 中扩展此规则。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
TypeScript 提供了一些指令注释,可用于更改其处理文件的方式。使用这些注释来抑制 TypeScript 编译器错误会降低 TypeScript 的整体有效性。相反,通常最好更正代码类型,以使指令变得不必要。
TypeScript 支持的指令注释为
// @ts-expect-error
// @ts-ignore
// @ts-nocheck
// @ts-check
此规则允许您设置要在代码库中允许的指令注释。
module.exports = {
  "rules": {
    "@typescript-eslint/ban-ts-comment": "error"
  }
};
在游乐场中尝试此规则 ↗
选项
此规则接受以下选项,并在 strict 配置中具有更严格的设置。
type DirectiveConfigSchema =
  | 'allow-with-description'
  | {
      descriptionFormat?: string;
    }
  | boolean;
type Options = [
  {
    'ts-check'?: DirectiveConfigSchema;
    'ts-expect-error'?: DirectiveConfigSchema;
    'ts-ignore'?: DirectiveConfigSchema;
    'ts-nocheck'?: DirectiveConfigSchema;
    minimumDescriptionLength?: number;
  },
];
const defaultOptionsRecommended: Options = [
  {
    'ts-expect-error': 'allow-with-description',
    'ts-ignore': true,
    'ts-nocheck': true,
    'ts-check': false,
    minimumDescriptionLength: 3,
  },
];
// These options are merged on top of the recommended defaults
const defaultOptionsStrict: Options = [{ minimumDescriptionLength: 10 }];
默认情况下,只允许 @ts-check,因为它启用而不是抑制错误。
ts-expect-error、ts-ignore、ts-nocheck、ts-check 指令
对于特定指令,true 值表示此规则将在找到任何使用该指令的地方报告。
- ❌ 错误
- ✅ 正确
allow-with-description
对于特定指令,'allow-with-description' 值表示此规则将在找到没有描述(在同一行)的指令时报告。
例如,使用 { 'ts-expect-error': 'allow-with-description' }
- ❌ 错误
- ✅ 正确
descriptionFormat
对于每种指令类型,您可以使用正则表达式指定自定义格式。只有与模式匹配的描述才允许。
例如,使用 { 'ts-expect-error': { descriptionFormat: '^: TS\\d+ because .+$' } }
- ❌ 错误
- ✅ 正确
minimumDescriptionLength
使用 minimumDescriptionLength 为指令使用 allow-with-description 选项时设置描述的最小长度。
例如,使用 { 'ts-expect-error': 'allow-with-description', minimumDescriptionLength: 10 },以下模式是
- ❌ 错误
- ✅ 正确
何时不使用它
如果您的项目或其依赖项不是以强大的类型安全性为目标进行架构的,那么始终遵守正确的 TypeScript 语义可能会很困难。您可能考虑使用 ESLint 禁用注释 针对这些特定情况,而不是完全禁用此规则。
进一步阅读
- TypeScript 类型检查 JavaScript 文件