Search code examples
typescriptreturneslintstatic-analysis

Is there a rule in eslint to deny "assign, then return" pattern?


I want to deny using the following pattern in code:

function do_something_bad() {
    // bad
    const x = do_something_else();
    return x;
}

function do_something_good() {
    // good
    return do_something_else();
}

It looks very weird for me, and is purely style issue, so eslint should be a good way to handle it (I'm open to suggestions, any other linter is also OK, I just have eslint configured, so ask about it). Is there any rule (or maybe plugin) I can install/enable to require only the "Good" option?

For background, I'm mostly python man, and it is inspired by flake8 R504 (from flake8-return plugin) error. It is also present in tslint Microsoft extensions, but they are "archived and read-only" (rule no-unnecessary-local-variable).


Solution

  • After some research I found out that "sonarjs" ESLint plugin has prefer-immediate-return rule (enabled by default) for exactly this case. Running eslint with this plugin reveals all such usages (as well as some other style defects).

    (I'm not affiliated in any way with this plugin)