typescripteslinttypescript-eslint

Is there an ESLint rule to prevent truthy checks


I want to avoid accidentally invoking Javascript's insane truthy system. Are there any ESLint rules to help with this? Especially in if statements. For example:

const a: number = 0;
const b: string | null = null;
if (a) { ... } // Should be an error.
if (b) { ... } // Should be an error.
if (a !== 0) { ... } // Ok
if (b !== null) { ... } // Ok

I thought no-implicit-coercion might do the job but it seems like it doesn't cover this case.


Solution

  • Yes, @typescript-eslint/strict-boolean-expressions.

    Technical explanation: it forbids usage of non-boolean types in expressions where a boolean is expected.

    In other words: it makes it so you have to explicitly pass booleans (false or true), not "truthy" things. Instead of if (a), you'd have to do if (a != null) or similar.

    (you commented this in 2020, just posting to have an answer 🙂)