Search code examples
eslinttypescript-eslint

How to prevent using only numbers if/else conditions (an ESLint rule?): e.g. if (myNumber) { /* ... */ }


I've recently found multiple bugs related to values being 0 in if/else statements. They were being handled as if they're false.

For example,

  if (viewState.latitude) { // 👈🏼️ I needed to add a !== undefined to handle when latitude is 0
    params.set(
      QUERY_PARAM_LATITUDE_KEY,
      viewState.latitude.toFixed(4).toString(),
    );
  }

How can I prevent these? I can't find an ESLint rule for this. It would be nice if I could prevent if (number) { formats. It seems like a really simple question though 🤷🏼️


Solution

  • strict-boolean-expressions

    Enabling this rule does make things more verbose. It has already caught more bugs though. It really is a tradeoff.

      if (viewState.latitude) {
        params.set(
          QUERY_PARAM_LATITUDE_KEY,
          viewState.latitude.toFixed(4).toString(),
        );
      }
    

    will error with

    Unexpected nullable number value in conditional. Please handle the nullish/zero/NaN cases explicitly  @typescript-eslint/strict-boolean-expressions`.
    

    More verbose

    Note: rightButton is a boolean | undefined

    // previously
    if (event.rightButton) {
    // now
    if (event.rightButton !== undefined && event.rightButton) {
    // or alternatively
    if (event.rightButton === true) {
    

    Eslint config

    module.exports = {
      "rules": {
        "@typescript-eslint/strict-boolean-expressions": "error"
      }
    };