Skip to content

typescript/no-extraneous-class Suspicious

⚠️💡 A dangerous suggestion is available for this rule.

What it does

This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace. This rule also reports classes that have only a constructor and no fields. Those classes can generally be replaced with a standalone function.

Why is this bad?

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).

This rule also reports classes that have only a constructor and no fields. Those classes can generally be replaced with a standalone function.

Examples

Examples of incorrect code for this rule:

ts
class StaticConstants {
  static readonly version = 42;

  static isProduction() {
    return process.env.NODE_ENV === "production";
  }
}

class HelloWorldLogger {
  constructor() {
    console.log("Hello, world!");
  }
}

abstract class Foo {}

Examples of correct code for this rule:

ts
const version = 42;
const isProduction = () => process.env.NODE_ENV === "production";

Configuration

This rule accepts a configuration object with the following properties:

allow_constructor_only

type: boolean

default: false

Allow classes that only have a constructor.

allow_empty

type: boolean

default: false

Allow empty classes.

allow_static_only

type: boolean

default: false

Allow classes with only static members.

allow_with_decorator

type: boolean

default: false

Allow classes with decorators.

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny typescript/no-extraneous-class
json
{
  "rules": {
    "typescript/no-extraneous-class": "error"
  }
}

References

Released under the MIT License.