Skip to content

Latest commit

 

History

History
126 lines (92 loc) · 2.92 KB

no-conditional-statements.md

File metadata and controls

126 lines (92 loc) · 2.92 KB

Disallow conditional statements (functional/no-conditional-statements)

💼🚫 This rule is enabled in the following configs: noStatements, ✅ recommended, 🔒 strict. This rule is disabled in the following configs: disableTypeChecked, ☑️ lite.

💭 This rule requires type information.

This rule disallows conditional statements such as if and switch.

Rule Details

Conditional statements are not a good fit for functional style programming as they are not expressions and do not return a value. Instead consider using the ternary operator which is an expression that returns a value:

For more background see this blog post and discussion in tslint-immutable #54.

❌ Incorrect

/* eslint functional/no-conditional-statements: "error" */

let x;
if (i === 1) {
  x = 2;
} else {
  x = 3;
}

✅ Correct

/* eslint functional/no-conditional-statements: "error" */

const x = i === 1 ? 2 : 3;
/* eslint functional/no-conditional-statements: "error" */

function foo(x, y) {
  return x === y // if
    ? 0
    : x > y // else if
      ? 1
      : -1; // else
}

Options

This rule accepts an options object of the following type:

type Options = {
  allowReturningBranches: boolean | "ifExhaustive";
};

Default Options

const defaults = {
  allowReturningBranches: false,
};

Preset Overrides

recommended and lite

const recommendedAndLiteOptions = {
  allowReturningBranches: true,
};

allowReturningBranches

true

Allows conditional statements but only if all defined branches end with a return statement or other terminal. This allows early escapes to be used.

function foo(error, data) {
  if (error) {
    return;
  }

  // ... - Do stuff with data.
}

"ifExhaustive"

This will only allow conditional statements to exist if every case is taken into account and each has a return statement or other terminal. In other words, every if must have an else and every switch must have a default case. This allows conditional statements to be used like do expressions.

const x = (() => {
  switch (y) {
    case "a":
      return 1;
    case "b":
      return 2;
    default:
      return 0;
  }
})();

Note: Currently this option is not useable with the no-else-return rule; else statements must contain a return statement.