noStaticOnlyClass
Este conteúdo não está disponível em sua língua ainda.
Diagnostic Category: lint/complexity/noStaticOnlyClass
Since: v1.0.0
Sources:
- Same as:
@typescript-eslint/no-extraneous-class
- Same as:
unicorn/no-static-only-class
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
- Whatever would be put on them, such as utility functions, are already organized by virtue of being in a module.
- As an alternative, you can import * as … the module to get all of them in a single object.
-
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).
Examples
Section titled ExamplesInvalid
Section titled Invalidcode-block.js:1:1 lint/complexity/noStaticOnlyClass ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Avoid classes that contain only static members.
> 1 │ class X {
│ ^^^^^^^^^
> 2 │ static foo = false;
> 3 │ static bar() {};
> 4 │ }
│ ^
5 │
ℹ Prefer using simple functions instead of classes with only static members.
code-block.js:2:10 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ ‘readonly’ modifier can only be used in TypeScript files
1 │ class StaticConstants {
> 2 │ static readonly version = 42;
│ ^^^^^^^^
3 │
4 │ static isProduction() {
Valid
Section titled ValidNotes on Mutating Variables
Section titled Notes on Mutating VariablesOne 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:
code-block.js:1:8 lint/complexity/noStaticOnlyClass ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Avoid classes that contain only static members.
> 1 │ export class Utilities {
│ ^^^^^^^^^^^^^^^^^
> 2 │ static mutableCount = 1;
> 3 │ static incrementCount() {
> 4 │ Utilities.mutableCount += 1;
> 5 │ }
> 6 │ }
│ ^
7 │
ℹ Prefer using simple functions instead of classes with only static members.
Do this instead: