Itai
Itai

Reputation: 417

Arrow function implicit return wrapped automatically with parenthesis

I'm using Visual Studio Code with Prettier, and function like this:

(token: string) => this.token = token

becomes:

(token: string) => (this.token = token)

I think it's makes it less readable... Is there a a way to prevent this?

Upvotes: 6

Views: 5517

Answers (3)

username1612308213
username1612308213

Reputation: 1

Here's a solution until a less opinionated code formatter comes along (please point it out to me if it already exists).

Open the following file:

  • Windows %USERPROFILE%\.vscode\extensions\esbenp.prettier-vscode-5.8.0\node_modules\prettier\index.js
  • macOS, Linux ~/.vscode/extensions/esbenp.prettier-vscode-5.8.0/node_modules/prettier/index.js

(where %USERPROFILE% is usually C:\Users\YourUsernameHere\)

If you're coming from the future, you may see a different version name for your esbenp.prettier-vscode-X.X.X folder. Modify the path accordingly.

Use Ctrl + F to search for case "AssignmentExpression": (there are around four or five occurrences) until you get to this little snippet of code. Change the pictured return true to return false. I found the statement on line 41587, but this will likely change in future versions of Prettier, so fall back on the Ctrl + F search.

Save the file, restart VSCode, and it works like magic.

I found that VSCode on macOS may get upset with you for fiddling around with the internals. There should be some settings icon in the popups that give you an option to ignore the error. Choose to ignore the error, then restart VSCode again and it should be working fine.

Upvotes: 0

saravana va
saravana va

Reputation: 1149

You can add config file to make custom configuration, It can be json, js, yaml etc, Please refer this link this may help you

https://prettier.io/docs/en/configuration.html

For Arrorw Function, Probably you have to use "arrowParens": "aviod" in your .prettierrc file if you are using json schema to avoid automatically adding parenthesis.

Upvotes: -3

bug-a-lot
bug-a-lot

Reputation: 2454

This is due to the no-return-assign rule. See https://eslint.org/docs/rules/no-return-assign.

Despite what you might think, your arrow function is equivalent to

(token: string) => {return this.token = token}

Yes, there's a return in there, and it gets "prettified" due to the assignment.

The only two options for this rule are to allow when parenthesis are present, or disallow always.

So to fix your "readability issue" either use the curly braces, or try to disable the rule (not recommended).

Upvotes: 5

Related Questions