src/content/docs/linter/rules/no-static-only-class.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/complexity/noStaticOnlyClass`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule doesn't have a fix. - The default severity of this rule is [**warning**](/reference/diagnostics#warning). - Sources: - Same as [`@typescript-eslint/no-extraneous-class`](https://typescript-eslint.io/rules/no-extraneous-class) - Same as [`unicorn/no-static-only-class`](https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-static-only-class.md){
"linter": {
"rules": {
"complexity": {
"noStaticOnlyClass": "error"
}
}
}
}
This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace.
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
IDEs can't provide as good suggestions for static class or namespace imported properties when you start typing property names
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).
class X {
static foo = false;
static bar() {};
}
class StaticConstants {
static readonly version = 42;
static isProduction() {
return process.env.NODE_ENV === 'production';
}
}
const X = {
foo: false,
bar() {}
};
export const version = 42;
export function isProduction() {
return process.env.NODE_ENV === 'production';
}
function logHelloWorld() {
console.log('Hello, world!');
}
class Empty {}
One case you need to be careful of is exporting mutable variables. While class properties can be mutated externally, exported variables are always constant. This means that importers can only ever read the first value they are assigned and cannot write to the variables.
Needing to write to an exported variable is very rare and is generally considered a code smell. If you do need it you can accomplish it using getter and setter functions:
export class Utilities {
static mutableCount = 1;
static incrementCount() {
Utilities.mutableCount += 1;
}
}
Do this instead:
let mutableCount = 1;
export function getMutableCount() {
return mutableField;
}
export function incrementCount() {
mutableField += 1;
}