eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: `prefer-short-arrow-method`
Description
ESLint has various rules to enforce methods or function declarations vs arrow functions. One that’s missing is a way to enforce the use of a short arrow function vs the use of a method with a single return value.
I.e., given this
is not used the following are equivalent:
// 1
const person = {
greet(name) {
return `Hello, ${name}`
}
}
// 2
const person = {
greet: (name) => {
return `Hello, ${name}`
}
}
// 3
const person = {
greet: (name) => `Hello, ${name}`
}
The object-shorthand
rule can be used to prefer option 1 over option 2. The arrow-body-style
rule can be used to enforce option 3 over option 2. However, there’s no way to enforce option 1 or 3 over the other.
I suggest to add a rule to prefer a short arrow function over a method with a single return value. I’m also fine with a rule that’s the other way around. For me it’s about consistency.
Fail
const person = {
greet(name) {
return `Hello, ${name}`
}
}
Pass
const person = {
greet: (name) => `Hello, ${name}`
}
Use the arrow-body-style
rule to deal with this situation.
const person = {
greet: (name) => {
return `Hello, ${name}`
}
}
Note that there's cases where the method needs to be defined on the prototype. One such example is Angular lifecycle hooks. See https://github.com/bahmutov/eslint-rules/issues/54, https://github.com/TristonJ/eslint-plugin-prefer-arrow/issues/17#issuecomment-1062210291, https://github.com/JamieMason/eslint-plugin-prefer-arrow-functions/issues/9 and https://github.com/angular-eslint/angular-eslint/issues/1002
So a way of excluding certain method names may be necessary. Otherwise, +1.