unicorn/no-static-only-class
Disallow classes that have only static members
fixable
A class with only static members has nothing to instantiate. It groups values and functions under a name, and a plain object does that with less syntax.
A class isn't reported if it extends another class, has a decorator, is empty, or has a member that an object can't have: a private #name, a static block, or in TypeScript a member marked readonly, declare, public, protected or private.
--fix-dangerously rewrites the class to an object. --fix doesn't, because code that calls new on the class or uses it as a type would stop working.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-static-only-class" = "error" # or "warn"Examples#
example.js1 problem
class Temperature {Use an object instead of a class with only static members.
static freezing = 32;
static toCelsius(fahrenheit) {
return ((fahrenheit - 32) * 5) / 9;
}
}example.jsNo problems
const Temperature = {
freezing: 32,
toCelsius(fahrenheit) {
return ((fahrenheit - 32) * 5) / 9;
},
};A class with a private member isn't reported:
example.jsNo problems
class Counter {
static #count = 0;
static next() {
return ++Counter.#count;
}
}Neither is one with a TypeScript modifier:
example.tsNo problems
class Limits {
static readonly maxRetries = 3;
private static attempts = 0;
}