@typescript-eslint/class-literal-property-style

Require constants on a class to be all readonly fields or all getters

has suggestions

Also called typescript-eslint/class-literal-property-style, typescript/class-literal-property-style

A class can expose a constant as a readonly field or as a getter that returns a literal. From the outside, you read both the same way. This rule picks one, so every class writes it the same way. By default it's the readonly field, which is shorter.

Only literals count: strings, numbers, booleans, null, regular expressions, and templates without ${}.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"@typescript-eslint/class-literal-property-style" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
# "fields" or "getters"
"@typescript-eslint/class-literal-property-style" = ["error", "fields"]

Examples#

example.ts1 problem
class Server {
  get host() {
    return "localhost";
  }
}
example.tsNo problems
class Server {
  readonly host = "localhost";

  // Not a literal.
  get url() {
    return `http://${this.host}`;
  }
}

A getter that has a setter with the same name can't become a readonly field, so the rule leaves it alone:

example.tsNo problems
class Server {
  get host() {
    return "localhost";
  }
  set host(value: string) {
    console.warn("host is fixed", value);
  }
}

Options#

OptionWhat it does
"fields" (default)Report a getter that only returns a literal.
"getters"Report a readonly field with a literal as its value.
example.tswith "getters"1 problem
class Server {
  readonly host = "localhost";
}
example.tswith "getters"No problems
class Server {
  get host() {
    return "localhost";
  }
}

With "getters", a field that the constructor assigns to isn't reported:

example.tswith "getters"No problems
class Server {
  readonly host = "localhost";

  constructor(host?: string) {
    if (host) this.host = host;
  }
}