Search code examples
eslinttslinttypescript-eslint

ES/TS Linting rule to check if i'm not iffing an array instead of array.length >= 1?


I've noticed a common mistake I make where I have a set of different ifs and some of them are strings or booleans, but some of them are an array.

But sometimes I forget it will always be defined and I have to actually check for:

if (array.length >= 1) instead of if (array).

Is there a TS/ES linting rule to check if I'm iffing something that will always return true? (Or specifically when I if an array which is already defined so the linter should know it will always return true)

I found this: https://eslint.org/docs/latest/rules/no-constant-condition but that will not warn me for this:

const array = []
if (array) console.log(array) // Wil always run

Solution

  • @typescript-eslint/no-unnecessary-condition is what you're looking for. It "disallows conditionals where the type is always truthy or always falsy".

    You'll need to set up typescript-eslint: its Getting Started and its Linting with Typed Linting.