Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: prefer-short-arrow-method #1737

Open
remcohaszing opened this issue Feb 24, 2022 · 2 comments
Open

Rule proposal: prefer-short-arrow-method #1737

remcohaszing opened this issue Feb 24, 2022 · 2 comments

Comments

@remcohaszing
Copy link
Contributor

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}`
  }
}
@fisker
Copy link
Collaborator

fisker commented Feb 24, 2022

object-shorthand?

@Samuel-Therrien-Beslogic
Copy link

Samuel-Therrien-Beslogic commented Dec 14, 2023

Note that there's cases where the method needs to be defined on the prototype. One such example is Angular lifecycle hooks. See bahmutov/eslint-rules#54, TristonJ/eslint-plugin-prefer-arrow#17 (comment), JamieMason/eslint-plugin-prefer-arrow-functions#9 and angular-eslint/angular-eslint#1002

So a way of excluding certain method names may be necessary. Otherwise, +1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants