Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 1.54 KB

no-unnecessary-condition.md

File metadata and controls

57 lines (40 loc) · 1.54 KB

Condition expressions must be necessary

Any expression being used as a condition must be able to evaluate as truthy or falsy in order to be considered "necessary". Conversely, any expression that always evaluates to truthy or always evaluates to falsy, as determined by the type of the expression, is considered unnecessary and will be flagged by this rule.

The following expressions are checked:

  • Arguments to the &&, || and ?: (ternary) operators
  • Conditions for if, for, while, and do-while statements.

Examples of incorrect code for this rule:

function head<T>(items: T[]) {
  if (items) {
    return items[0].toUpperCase();
  }
}

const foo = 'foo';
if (foo) {
}

Examples of correct code for this rule:

function head<T>(items: T[]) {
  if (items.length) {
    return items[0].toUpperCase();
  }
}

declare const foo: string;
// Necessary, since foo might be ''. (If undesired, consider using `strict-boolean-expressions` rule)
if (foo) {
}

Options

Accepts an object with the following options:

  • ignoreRhs (default false) - doesn't check if the right-hand side of && and || is a necessary condition. For example, the following code is valid with this option on:
function head<T>(items: T[]) {
  return items.length && items[0].toUpperCase();
}

When Not To Use It

The main downside to using this rule is the need for type information.

Related To