no-extraneous-class
Disallow classes used as namespaces.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/strict"
可启用此规则。
此规则报告类何时没有非静态成员,例如专门用作静态命名空间的类。
¥This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace.
来自 OOP 范式的用户可以将其实用函数封装在一个额外的类中,而不是将它们放在 ECMAScript 模块的顶层。在 JavaScript 和 TypeScript 项目中通常不需要这样做。
¥Users who come from a OOP paradigm may wrap their utility functions in an extra class, instead of putting them at the top level of an ECMAScript module. Doing so is generally unnecessary in JavaScript and TypeScript projects.
-
封装类在不添加任何结构改进的情况下为代码增加了额外的认知复杂性
¥Wrapper classes add extra cognitive complexity to code without adding any structural improvements
-
无论要放在它们上面的是什么,例如效用函数,都已经通过模块进行了组织。
¥Whatever would be put on them, such as utility functions, are already organized by virtue of being in a module.
-
或者,你可以
import * as ...
模块以将它们全部放在单个对象中。¥As an alternative, you can
import * as ...
the module to get all of them in a single object.
-
-
当你开始输入属性名称时,IDE 无法为静态类或命名空间导入的属性提供良好的建议
¥IDEs can't provide as good suggestions for static class or namespace imported properties when you start typing property names
-
当所有未使用的变量等都在类中时,静态分析代码会更加困难(参见:在 TypeScript 中查找死代码(和死类型))。
¥It's more difficult to statically analyze code for unused variables, etc. when they're all on the class (see: Finding dead code (and dead types) in TypeScript).
此规则还报告仅具有构造函数而没有字段的类。这些类通常可以用独立的函数替换。
¥This rule also reports classes that have only a constructor and no fields. Those classes can generally be replaced with a standalone function.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-extraneous-class": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-extraneous-class": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
class StaticConstants {
static readonly version = 42;
static isProduction() {
return process.env.NODE_ENV === 'production';
}
}
class HelloWorldLogger {
constructor() {
console.log('Hello, world!');
}
}
abstract class Foo {}
Open in Playgroundexport const version = 42;
export function isProduction() {
return process.env.NODE_ENV === 'production';
}
function logHelloWorld() {
console.log('Hello, world!');
}
abstract class Foo {
abstract prop: string;
}
Open in Playground备择方案
¥Alternatives