Search code examples
typescript-eslint

@typescript-eslint/strict-boolean-expressions: Union type should be considered with allowOptions


An example.

play.

declare const str: string
if (str) { } good

declare const num: number
if(num) {} // good

declare const u: string | number
if(u) {} // Unexpected value in conditional. A boolean expression is required.ESLint@typescript-eslint/strict-boolean-expressions

I think the union type u should not be reported.


Solution

  • You are wrong. The rule strict-boolean-expressions is described as:

    Forbids usage of non-boolean types in expressions where a boolean is expected. boolean and never types are always allowed. Additional types which are considered safe in a boolean context can be configured via options.
    

    Keep in mind that additional types can be configured via options. So let's take a look how default options looks like

    const defaultOptions: Options = [
      {
        allowString: true,
        allowNumber: true,
        allowNullableObject: true,
        allowNullableBoolean: false,
        allowNullableString: false,
        allowNullableNumber: false,
        allowNullableEnum: false,
        allowAny: false,
        allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
      },
    ];
    

    In my opinion that perfectly explains why the first two examples work and the last one fails