ESLint如何检测Angular项目中未使用的私有类属性?
解决方案
你当前配置的@typescript-eslint/no-unused-vars规则本身不覆盖类私有属性的未使用检测,需要新增专用规则实现需求,操作如下:
- 第一步:确认你本地安装的
@typescript-eslint/eslint-plugin版本≥v5.34.0,该规则是此版本新增的能力。 - 第二步:打开你的
.eslintrc.json配置文件,在*.ts对应的rules配置块中新增以下规则:
"@typescript-eslint/no-unused-private-class-members": "error"
修改后对应规则段示例如下:
"rules": { // 保留你原来的其他规则不变 "@typescript-eslint/no-unused-vars": [ "error", { "argsIgnorePattern": "^_" } ], // 新增下面这行 "@typescript-eslint/no-unused-private-class-members": "error", // 其他原有规则保持不变 "no-case-declarations": "off", }
注意事项
- 该规则仅会检测标记为
private的类成员,public、protected修饰的成员不会触发检测 - 若你的私有属性仅在Angular组件的HTML模板中调用,该规则目前无法识别模板内的引用,会出现误报。这种情况你可以给对应属性添加单行忽略注释
// eslint-disable-next-line @typescript-eslint/no-unused-private-class-members,或者调整规则配置添加忽略前缀,和no-unused-vars保持一致:
"@typescript-eslint/no-unused-private-class-members": ["error", { "ignorePrivateNamesWithUnderscore": true }]
配置后名称以下划线开头的私有成员不会触发该规则检测。
内容的提问来源于stack exchange,提问作者Vilius Gudžiūnas
相关产品推荐
相关产品推荐

