@typescript-eslint/class-literal-property-style
Require constants on a class to be all readonly fields or all getters
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:
[lint.rules]
"@typescript-eslint/class-literal-property-style" = "error" # or "warn"Every option, set to its default:
[lint.rules]
# "fields" or "getters"
"@typescript-eslint/class-literal-property-style" = ["error", "fields"]Examples#
class Server {
get hostLiterals should be exposed using readonly fields.() {
return "localhost";
}
}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:
class Server {
get host() {
return "localhost";
}
set host(value: string) {
console.warn("host is fixed", value);
}
}Options#
| Option | What it does |
|---|---|
"fields" (default) | Report a getter that only returns a literal. |
"getters" | Report a readonly field with a literal as its value. |
"getters"1 problemclass Server {
readonly hostLiterals should be exposed using getters. = "localhost";
}"getters"No problemsclass Server {
get host() {
return "localhost";
}
}With "getters", a field that the constructor assigns to isn't reported:
"getters"No problemsclass Server {
readonly host = "localhost";
constructor(host?: string) {
if (host) this.host = host;
}
}