yskkin
yskkin

Reputation: 890

eslint: no-implicit-coercion for if conditionals

I'm using eslint with @typescript-eslint/eslint-plugin in TypeScript.

Is it possible to warn the following code for using any type in if conditional? I tried no-implicit-coercion rule but it did not work.

const foo = (a: any) => {
  if (a) { // this should be warned
    return 42;
  } else {
    return false;
  }
}

Upvotes: 2

Views: 1408

Answers (1)

Lauren Yim
Lauren Yim

Reputation: 14088

You're looking for @typescript-eslint/strict-boolean-expressions.

By default, it forbids any in conditionals, but also forbids nullable booleans, nullable strings, and nullable numbers. To only forbid any you could use this configuration:

"rules": {
  "@typescript-eslint/strict-boolean-expressions": [2,  {
    "allowNullableBoolean": true,
    "allowNullableString": true,
    "allowNullableNumber": true
  }]
}

Personally, I don't recommend this though and I would keep the rule with the default settings, as it could prevent bugs like this (albeit a contrived example):

declare const maybeNumber: number | null
if (maybeNumber) {
  // number could actually be null, 0, or NaN!
  console.log('maybeNumber is not null!') // oops
  let thisIsNaN = 123 / maybeNumber
}

Also, you could also use @typescript-eslint/no-explicit-any to avoid any in your codebase entirely; use unknown instead.

Upvotes: 2

Related Questions