Search code examples
typescripteslinttypescript-eslint

Typescript or ESLint rule to disallow default returns (in lambdas)?


I came across this error in my code and I felt it should have been picked up by Lint or Typescript itself. Is there is a plugin / additional setting I can set to make "default return" a compile warning?

What I wrote:

activeRegion = regions.find( region => { region.countryCode === activeCountryCode } )

What I should have written:

activeRegion = regions.find( region =>  region.countryCode === activeCountryCode  )

The second does what you want, and returns the region where the condition is true.

The first, because you have actually written a function, expects a return. BUT because JS has a concept of default returns, what it actually becomes is this

activeRegion = regions.find( region => { 
   region.countryCode === activeCountryCode
   return undefined;
 } )

which of course is nonsense in this case (nothing will be found), so is there a lint rule that would stop these sneaky default returns from getting added in?


Solution

  • The rules array-callback-return and no-unused-expressions will both be triggered by this code.

    To manually add a rule, here's how to do it, from the documentation:

    In .eslintrc.js:

    {
        ...
        "rules": {
            "array-callback-return": "error",
            "no-unused-expressions": "error",
        }
    }
    

    Or in yaml:

    rules:
      array-callback-return: error
      no-unused-expressions: error
    

    An easier way to to work with eslint is by using plugins, or extending a base configuration.
    This adds a set of rules, without having to add them one by one.

    For example in .eslintrc.js:

      ...
      extends: ["airbnb-typescript", ... ],
    

    or

      ...
      plugins: ["@typescript-eslint", ...],
    

    Two commonly used are the one from Airbnb, and the Typescript plugin but there are more.
    Note that you need to install the package before adding it to the eslint configuration.

    More information in the eslint documentation.